I'm trying to use Chrome's dev tools to debug the flow of javascript on a page. I have a 3rd party system that loads javascript that dynamically adds a SCRIPT tag to the HEAD element on the page using some code like:
var head= document.getElementsByTagName("head")[0];
var el = document.createElement('script');
el.type = 'text/javascript';
el.src = '.js';
head.appendChild(el);
How can I catch the "anotherjsscript.js" as it is dynamically loaded and debug into that?
I'm trying to use Chrome's dev tools to debug the flow of javascript on a page. I have a 3rd party system that loads javascript that dynamically adds a SCRIPT tag to the HEAD element on the page using some code like:
var head= document.getElementsByTagName("head")[0];
var el = document.createElement('script');
el.type = 'text/javascript';
el.src = 'https://address./anotherjsscript.js';
head.appendChild(el);
How can I catch the "anotherjsscript.js" as it is dynamically loaded and debug into that?
Share Improve this question asked Feb 12, 2016 at 11:11 Dave PottsDave Potts 1,6432 gold badges24 silver badges38 bronze badges2 Answers
Reset to default 5Although BenG's answer will cover most cases, my case was badly obfuscated with a different filename dynamically served each time. My solution was to add an event listener for "Script first statement" and then laboriously work through all the other scripts until I hit the one I wanted.
Option 1
I just used your code above pointing to jQuery Validation:-
var head= document.getElementsByTagName("head")[0];
var el = document.createElement('script');
el.type = 'text/javascript';
el.src = 'https://cdnjs.cloudflare./ajax/libs/jquery-validate/1.14.0/jquery.validate.js';
head.appendChild(el);
After letting the page run for the 1st time, you will see the request under the Network Tab, right click on the script and select Open in source panel :-
then add your break point and refresh the page again:-
Which should then get hit.
Option 2
Another option is to create a function like below, which gets the script content, prepend a debugger
and set the scripts text to the content:-
function debugScript(url){
var xmlHttp = new XMLHttpRequest();
xmlHttp.open( "GET", url, false );
xmlHttp.send( null );
var script = 'debugger; ' + xmlHttp.responseText;
var head = document.getElementsByTagName("head")[0];
var el = document.createElement('script');
el.type = 'text/javascript';
el.text = script;
head.appendChild(el);
}
debugScript('https://cdnjs.cloudflare./ajax/libs/jquery-validate/1.14.0/jquery.validate.js');
The breakpoint will get hit as long as the developer tools is open.