最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

How to use Chrome dev tools to debug javascript tag added dynamically to a page's head element? - Stack Overflow

programmeradmin1浏览0评论

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 badges
Add a ment  | 

2 Answers 2

Reset to default 5

Although 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.

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论