9

I* am using client-side JS to parse XML files and generate complex JS code to eval as a result. (Generating re-usable functions that are kicked off by a runtime.) However, I need to debug the code being generated, and would like to use Chrome's built-in breakpoints, stepping, watch windows, etc.

Is there an easier way to do this than:

  • Dump the generated JS string to the console and/or window.
  • Copy the JavaScript
  • (optional) Run the JS through a prettifier like JSBeautifier.
  • Paste the JS into a file that is loaded via <script src="..."> in another web page.

* actually, a friend of mine was doing this, not me

1 Answer 1

19

Instead of using eval, and instead of manually copy/pasting into a separate file, you can dynamically load the JS directly into the page that generated it by using a data uri on a dynamically-created <script> element. With this approach, Chrome's Developer Tools (and Firebug) allow you to pick the data-URI as a script, turn on the Pretty Print, set breakpoints, and away you go.

var js = createMyJSCodeString();
addCode(js); // Right now! Debuggable!

// Dynamically evaluate JavaScript-as-string in the browser
function addCode(js){
  var e = document.createElement('script');
  e.type = 'text/javascript';
  e.src  = 'data:text/javascript;charset=utf-8,'+escape(js);
  document.body.appendChild(e);
}
Sign up to request clarification or add additional context in comments.

6 Comments

Did you just... answer yourself? Sounded like you already talked about this in your question.
@TheZ Yes, I did. This is an accepted practice on Stack Overflow for adding to the knowledge base. There is now even a checkmark to press for automatically adding an answer as you post the question, which is what I used here.
So, what does createMyJSCodeString do? You said it parses XML files?
@lbstr As I understand it, it runs through XML files and generates the contents of functions by concatenating strings for various child elements and such. (The XML is a custom programming language representation.) It would certainly possible to generate the functions as closures--without any strings/eval--but there is a belief that doing it once this way will make a noticeable impact on the end speed.
(in case I google this again.) This can also be used to debug errors with new Function
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.