For a specific example, take a look at the haystack.js
script from How Big is Your Haystack?
I've been searching for a solution and it seems that using the //# sourceURL=name.js
comment is the way to go. However, I am struggling with the process of actually implementing this (maybe I'm just not getting it).
Most resources point to Debugging JavaScript, but unfortunately the demo there is broken due to a same-origin error. Other examples available do not offer much help when dealing with an external script like in this case.
I attempted to use Live Edit to add the sourceURL comment, but so far the eval script doesn't show up in the Sources tab.
Could someone walk me through the steps required to complete this task?
UPDATE: This has turned out to be quite an intriguing yet frustrating challenge. The website itself adds unnecessary complexity to the task with the following issues:
The haystack.js script contains
document.write()
statements which need to be removed before reloading the script to prevent clearing the DOM.The author uses a peculiar form of code obfuscation. Therefore, any code modifications (including adding the
sourceURL
) must happen after removing the obfuscation but before the eval stage.
I managed to find a workaround. After loading jQuery into the page, I executed the following script:
$.ajax({
url: '/js/haystack.js',
dataType: 'text'
}).done(function(data) {
// Remove document.write() statements and add sourceURL comment after deobfuscating
var refactored = data.replace(/return d/, "return d.replace(/document\.write[^;]+;/g, '') + '\\n//# sourceURL=haystack.js\\n';");
$('head').append('<script type="text/javascript">' + refactored + '</script>');
});
Now, haystack.js appears in the (no domain) tree of the Sources tab. Breakpoints can be set, however some strange behavior occurs. It seems that the DOM event handlers are still attached to the original script (breakpoints in reloaded script handlers are never triggered). Re-executing pageInit() reattaches the handlers to the modified script, but page updates remain unpredictable. It's unclear why this inconsistency persists. Even though I can step through the code and everything looks normal, the page updates seem delayed. Undoubtedly, the fact that the code violates many javascript best practices plays a role in this issue.