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

后端 未结 6 1063
闹比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:18

    The simplest way is probably document.scripts

    0 讨论(0)
  • 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
    });  
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
    <script>
      console.log("Inline script");
    </script>
    <script>
      function bla() {
        console.log("Other inline script");
      }
    </script>

    0 讨论(0)
  • 2020-12-03 19:22

    try this

    var scripts = document.getElementsByTagName("script");
    
    0 讨论(0)
  • 2020-12-03 19:23

    Here you go --

    (function () { 
            'use strict';
            let logscript = function () {
                let js = document.scripts;
                for (let i = 0; i < js.length; i++) {
                    if (js[i].src) {
                            console.log(i, js[i].src);
                        } else {
                            console.log(i, js[i].innerHTML);
                    }   
                }
            };
            if (document.readyState === 'complete') {
                    logscript();
            } else {
                    window.addEventListener('load', logscript);
            }
    })();
    
    
    0 讨论(0)
  • 2020-12-03 19:27

    Without jQuery :

    var scripts = document.getElementsByTagName("script");
    

    With jQuery :

    var scripts = $("script");
    
    0 讨论(0)
  • 2020-12-03 19:28

    You would do:

    var scripts = document.getElementsByTagName( 'script' );
    

    Now scripts is a NodeList (like an array), and you can access each one using scripts[0], scripts[1] and so on.

    0 讨论(0)
提交回复
热议问题