Dynamically load code and get parsing error line number

I have a tool similar to JSFiddle which allows me to dynamically inject javascript and run it on the page. The code can be several lines and usually will be.

Unfortunately, if there is an exception in the code I entered, I cannot get the exception line number if I use eval () to run the code.

I found a partial solution that instead of using

try{ eval(code); } catch(e) { processException(e); } 

to do something like this:

 var s = document.createElement('script'); s.appendChild(document.createTextNode( "try{\n" + code + "}catch(e){processException(e)}")); document.body.appendChild(s); 

Now, if the code throws an exception and I look at the stack trace (in my function processException ()), I can get the line number of the exception (in firefox and chrome, anyway).

This is good and good if it is actually a run-time exception, such as a variable that is not defined. The problem is a syntax parsing error, such as inconsistent parsers, etc. I get nothing.

Is there a crazy workaround for this that works on firefox and chrome at least? Eval inside eval in script tag inside Function object? I try my best and found nothing.

+7
source share
3 answers

I finally found a reasonable solution.

First I set window.onerror for some function. This does not give a full stack trace, but will get a file and line number.

Then I do this:

 var s = document.createElement('script'); s.appendChild(document.createTextNode( "var someUniqueGlobalName = function () {\n" + code + "\n};"; document.body.appendChild(s); 

Please note that this does not actually run my code, as it just creates a function (in the global area named "someUniqueGlobalName"), which of course I really came up with a different name every time I do this).

If there is a syntax error, it will be clamped in the window.onerror function, and I can get the error type and line number (which, of course, I have to subtract it from, since I added one line to the beginning).

Now I have disabled window.onerror.

Finally, I run the code by calling someUniqueGlobalName () in a try / catch block. Here I can get a full stack trace with line numbers if there is a runtime error.

+2
source

You can go one step further and integrate JSLINT: https://github.com/douglascrockford/JSLint

It's quite simple .. here is a quick test ...

Download: https://raw.github.com/douglascrockford/JSLint/master/jslint.js

jshint_test.html:

 <script type="text/javascript" src="jslint.js"></script> <script> var result = JSLINT("var some = true;\nif (some) {"); if (result) { alert('Looking good'); } else { var error_message = ''; for (i in JSLINT.errors) { var error = JSLINT.errors[i]; error_message += error.reason + ' on line: ' + error.line + ' character: ' + error.character + "\n"; } alert(error_message); } </script> 

Check the documentation. The second argument to JSLINT is the options object. There are tons of options.

+1
source
+1
source

All Articles