JavaScript try/catch and ajax reporting - javascript

There's something I'd like to do with my JavaScript deployments, and I'm looking for a really slick way to do it.
I'd like to run a try/catch on my code, which shouldn't be super impressive or complicated, but here's what I would like to do when I have a failure: let the dev team know, rather than waiting for that one-off customer that cares enough to write an email on the chance he notices something that breaks.
My initial thought was to write a support submission object which I could code to take any random data (i.e., report.submit(issue_data);), and create an ajax call to my server that silently adds the data to an inbox or a database or whatever.
I thought I could do it something like:
try {
some_code();
} catch(e) {
do_instead();
report.submit(issue_data);
report.update(); //Could perhaps show the users a history of errors
}
But, I'd like to see if there's a better solution...better as in solving an unseen flaw here, doing things more seamlessly, advice on how to deal with failures of the submission system, perhaps using the prototype in some exciting way, etc.
Also, my simple solution here has a lot of limitations that could make the whole thing semi-useless, such as not being able to indicate the specific part of the code that failed, line numbers, conditions to create failure, browser version, etc.

The big problem with these is that you have to be able to get those reports back. What we've done on my project is to have a logger REST resource and use log4javascript's AjaxAppender.

A little more info:
}catch(e){
alert(e.description);
}
But other than that your implementation looks pretty good to me my friend.

Related

How to organize JS functions using objects

I would like to know if organizing JS functions in object notation is a good or bad practice. The intention is to keep js organized/easy to maintain.
Example:
var helper = {
myAlert: function(){
return alert('Alert from helper');
},
toLowerCase: function(){
var str = document.getElementById("txt").innerHTML;
return alert(str.toLowerCase());
}
}
Html:
<body>
<h1 onclick="helper.myAlert()">Hello Plunker!</h1>
<p id="txt" onclick="helper.toLowerCase()">Testing LowerCaseFunction</p>
</body>
Plunker
Thanks in advance!!!
code organization is an strategic topic when it comes to make software survive more than a couple of years yet this is also a very opinionated terrain.
You can make a nice job by keeping semantically related functions near each other under the same namespace, or even make it related to the user story being solved, it can be done in many ways.
If you want to know this approach is good enough, simulate an iteration on it, add a new feature and see what happens to the code.
The code avoids duplication? It gets reusable? Is it easy to locate and relate with the user needs? If so, then it will help you.
Finally, if applicable consider to use some module builder, webpack or browserify for example, so you will be able to not only separate your modules logically but "physically" too.
For me it is a good practice. When working with little projects, you do do see it important, but in large projects you are almost obliged to do it.
simply imagine you are making a chat website, you will need to create function that will delete messages, add messages. you can simply do it as you did it up.
var messages = {
remove:function{//remove code},
add:function{//add code}
}
in this way you can define contacts management object as
var contacts = {
remove:function{//remove code},
add:function{ //add code},
block:function{//block code}
}
This isn't really an answer per se but too long for a comment:
Since you are asking about best practices I'd like to point out a few things in your sample:
onclick. Just...don't. You don't want to grep through your JS trying to diagnose a behavioral problem only to realize 8 hrs in that its being called from HTML. That's a maintenance nightmare waiting to happen.
innerHTML again, just...don't. Unless you are working with HTML. 9 times out of 10, textContent will do and you can assign to it without security risk. Google 'innerHTML security risk' for more info.
alert alert blocks. Blocks your whole browser until you click annoying box. And which of your 50 open tabs was it in? Blocking is bad. Use console.log. You're a dev, and you do have devtools open right?
Your toLowerCase function. You mix data access (getting the DOM element's text) with data transformation. Bad idea.
Note that none of these are particular to JavaScript, they apply to pretty much all UI coding: don't mix business logic with the presentation layer, don't block user interactions, use the principle of least privilege, don't mix data access with data processing, etc. And all of the above issues are bigger problems than whether or not you namespace some functions.

Degrees of JS vulnerability

Never trust the client. It's my coding mantra. All javascript can, with enough effort, be overwritten or compromised. The thing I want to understand is how.
Let's say I wrote a function checkStep() for a game - each time the player moves one space, it polls the server to check for any events: HP regeneration, enter random battle, move to next map, etc. I asked myself "self, how would I go about rewriting or disabling this function?" Research turned up some conflicting results. Some sources say functions can be directly redefined from the console, others say it would be a much more involved process.
My question is this: what would a player have to do to rewrite or disable my checkStep() function? Can they simply redefine it from the console? Would they have to rip, modify, and re-host my code? How would you do it?
Please note, I'm not asking how to make this function secure.
The first person to leave an answer/comment along the lines of "you
can try minifying it, but it still wont be secure" or "put in some
server-side checks" is getting bludgeoned with a semicolon, as an
example to the rest.
You could use a web debugging proxy like Fiddler to do this for your local machine. Programs like this allow you to intercept content you download and fiddle with it. So you could write a new version of the function, then use the program to replace it with your version when the file is downloaded from the server. Then, for your local machine, the code would run with the new function in place. The web session manipulation page on the Fiddler site has a few more details.
There is no reason to use any Javascript or browser a even.
If a normal user can use their browser to play the game then any user can use any program to communicate with the server and send it anything they want. The server is not able to know if someone is using a browser to connect to it or not.
This applies to anything. A game server doesn't know if the user is connecting to it through the official game client. Since the official game is closed source it would be easy to fall into trusting it even though it is possible to reverse engineer the protocols used and use anything to connect to the server.
Complex things like creating a malicious game client, or using a proxy to alter content before it makes it to the browser are technically valid points, however that seems like a lot of effort for something which is very simple to do.
var checkStep = function() {
... // your original function
}
// later on
checkStep = function() {
alert('foo');
}
It is perfectly valid in JavaScript to change what function a variable holds. Any function you define can be redefined on the client side. This can be done by other script files loaded by the browser which use conflicting variable names, scripts injected via XSS, or by the user bringing up the console.

Download a file from a site (partly written in Javascript) using Python

I'm trying to use Python to download a voice file (mp3) from this site:
I've tried to use mechanize and twill but I haven't got the proper result. I've heard about selenium as well. Anyway, I don't even know if it makes sense technically (mechanize + Javascript).
I was looking for an answer and finally I've found this solution.
It seems like a similar problem to mine but I have absoutely no idea what should I put instead of the 4th line.
If you have any proposition (maybe completely different to mine) I'll be glad to see it.
(Moving to answer to get more space)
Thanks for pointing me to selenium, I didn't know that and it looks cool; anyways: I had a quick look and the js seems to fire an ajax request, that yields no apparent result -- I guess the audio transfer is done some way in the background via flash or so; anyways: what about using the service they offer: developer.ivona.com instead of trying hacking your webservice out of the demo interface..?
Anyways, here it is the hacked web-service you asked for:
This is the URL you want to GET:
"http://www.ivona.com/voicetest.php?rtr=1&t2r=%(the_text)s..&v2r=dXNfc2FsbGk.&lang=us" % dict(
the_text=base64.b64encode("Hello, world!"),
the_voice=base64.b64encode("us_salli"),
)
You can test that with, for example, mplayer:
mplayer "http://www.ivona.com/voicetest.php?rtr=1&t2r=SGVsbG8sIHdvcmxkIQ==..&v2r=dXNfc2FsbGk.&lang=us"
And, from Python, use urllib to retrieve and store somewhere.
Beware that, since this is an unauthorized use, you might get blocked / incur in legal issues / etc. -- don't use in a production application!

New ActiveXObject('Word.Application') creates new winword.exe process when IE security does not allow object to be created

We are using MS Word as a spell checker for a few fields on a private company web site, and when IE security settings are correct it works well. (Zone for the site set to Trusted, and trusted zone modified to allow control to run without prompting.)
The script we are using creates a word object and closes it afterward. While the object exists, a winword.exe process runs, but it is destroyed when the Word object is closed.
If our site is not set in the trusted zone (Internet zone with default security level) the call that creates the Word object fails as expected, but the winword.exe process is still created. I do not have any way to interact with this process in the script, so the process stays around until the user logs off (users have no way to manually destroy the process, and it wouldn't be a good solution even if they did.)
The call that attempts to create the object is...
try {
wordApplication = new ActiveXObject('Word.Application');
} catch(error) {
// irrelevant code removed, described in comments..
// notify user spell check cannot be used
// disable spell check option
}
So every time the page is loaded this code may be run again, creating yet another orphan winword.exe process.
wordApplication is, of course, undefined in the catch block.
I would like to be able to detect the browser security settings beforehand, but I have done some searching on this and do not think that it is possible.
Management here is happy with it as it is. As long as IE security is set correctly it works, and it works well for our purposes. (We may eventually look at other options for spell check functionality, but this was quick, inexpensive, and does everything we need it to do.)
This last problem bugs me and I'd like to do something about it, but I'm out of ideas and I have other things that are more in need of my attention.
Before I put it aside, I thought I'd ask for suggestions here.
I have not found an answer to this problem, and I am disturbed at what the problem implies about Internet Explorer security (I forgot to mention in my previous post the version I am using : IE 7.)
However, I did implement a workaround that I am not happy with, but nevertheless feel more comfortable with than no check at all...
The code now attempts to open another object first, and if that fails the code assumes that Word will not open either and issues an error. From this point on, no more calls to new ActiveXObject() will be made and any attempt at a spell check will result in an error.
try {
oMSInfo = new ActiveXObject('Msinfo32.MSInfo.1');
} catch (error) {
// error handling code not shown...
return;
}
This object does not start a new process when the call to new ActiveXObject() fails. It also does not have a noticable affect on system resources.
If your browser creates an instance of an object, the object itself is not blocked by the browser security policies, except it is a security leak.
Try "application.visible=true", or "application.show()" to find out, where the application is asking for user interaction.
Hint: 'typeof application=="undefined"' means, the variable 'application' is not defined, where 'typeof application=="unknown"' means, more or less, it is a defined variable, stuffed with an external, proprietary object and if you really need to know how to handle it, read the manual -- pressing [F11] in any open window of the mentioned application could help in that case.
Might be a useful resource: https://learn.microsoft.com/en-us/office/vba/api/Word.Application

Is this a suitable case in which using dynamic function creation would be justified?

I'm currently developing a tutorial site for teaching the fundamentals of Web development (HTML, CSS, and JavaScript, for starters). I'd like a setup where I could give in-depth coverage of all sorts of topics and then provide a basic sandbox environment where the user could write code which solves the question asked at the end of each tutorial section.
For example, if I'd covered multiplication in a previous tutorial, and the user had just finished a lesson on functions being capable of returning values, I might request that they submit a function which returns the product of two parameters.
Is this not the perfect instance in which using dynamic function creation would be considered a good idea? Let's look at an example.
<script>
function check()
{
eval('var f = ' + document.getElementById('user_code').value);
if (f(5, 10) == 50)
{
// user properly wrote a function which
// returned the product of its parameters
}
}
</script>
Is this at all a bad idea? If so, please explain.
This sounds like it could work. However, the biggest challenge in your environment might be error handling. Students will surely make all sorts of errors:
Compile time errors, that will be detected in eval()
Run time errors, that will be detected when you call the function
Undetectable run time errors, such as an infinite loop or a stack overflow
A more elaborate approach might parse the entered Javascript into a parse tree representation, then compare it to an expected parse tree. If it does not match, then point out what might be wrong and have the student try again. If it does match, then you can eval() and call the function, knowing that it will do what you expect.
Implementing a lexer and parser for Javascript in Javascript would be challenging but certainly not impossible.
Should work as long as you're operating this in a closed environment. Eval opens you up to code injection attacks so I wouldn't put this on a publicly accessible web site, but if it's completely contained within your class room you should be ok.
The code would work, but what if there is an error both syntactically or otherwise ? Perhaps use a try block to catch any error and display it to the user would help things a little...
Not sure if this helps.
Sounds like you want to remake Firebug or even the new Developer Tools in IE8. Due to that, I'm going to have to say there is never a useful case. Not to mention the possibilities of script injection if this site goes public.
In your case, I feel that there is nothing wrong with this. Alternatively you can run the code by using new Function() to build stuff first and then run it. In theory, this would separate the stages of "compiling" and executing. However eval will check the code first and throw errors anyway:
var usercode = document.getElementById('user_code').value;
try {
var f = new Function( 'a','b','return (' + usercode + ')(a,b);' );
if ( f( 5, 10 ) ) {
// user properly wrote a function which
// returned the product of its parameters
}
else {
// user wrote code that ran but produced incorrect results
}
}
catch ( ex ) {
// user wrote something really bad
}
The problem with doing things in this manner is that the exceptions thrown may be nonsensical. "foo;;=bar" will report a "missing ) in parenthetical" error while eval will throw a propper syntax error. You could bypass this by (regexp) grabbing the parameters and body from the user code first and then building it. But then, how would this be any better than an eval?
I think that your real problem will be helping users avoid the pitfalls of implicit globals. How are you going to help users avoid writing code that only works the second time it runs because a global was set the first time? Will you not need to implement a clean sandbox every run? I would take a look at how jsbin.com, firebug and similar tools handle these things.
My feeling is that you should go with eval for now and change it for more elaborate stuff later if the need arrises.

Categories

Resources