How to collect all script tags of HTML page in a variable

后端 未结 6 1074
闹比i
闹比i 2020-12-03 19:01

I would like to collect all the code section present in the HTML page in some variable.

What should be the simpler w

6条回答
  •  春和景丽
    2020-12-03 19:19

    To get a list of scripts you can use

    • document.getElementsByTagName("script"); by tag
    • document.scripts; Built-in collection
    • document.querySelectorAll("script"); by selector
    • $("script") jQuery by selector

    var scripts = document.getElementsByTagName("script");
    for (var i = 0; i < scripts.length; i++) {
      if (scripts[i].src) console.log(i, scripts[i].src)
      else console.log(i, scripts[i].innerHTML)
    }
    
    // To get the content of the external script 
    // - I use jQuery here - only works if CORS is allowing it
    
    // find the first script from google 
    var url = $("script[src*='googleapis']")[0].src; 
    
    $.get(url,function(data) { // get the source 
      console.log(data.split("|")[0]); // show version info
    });  
    
    
    

提交回复
热议问题