如何在变量中收集HTML页面的所有脚本标记

Ash*_*tal 6 html javascript html-parsing

我想<script> ....</script>在一些变量中收集HTML页面中存在的所有代码部分.

什么应该是更简单的方法,任何想法如何使用JavaScript检索它.

任何帮助将不胜感激.

mpl*_*jan 27

获取可以使用的脚本列表

  • document.getElementsByTagName("script"); 按标签
  • document.scripts; 内置系列
  • document.querySelectorAll("script"); 通过选择器
  • $("script") 选择器jQuery

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
});  
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)


Esa*_*ija 7

最简单的方法可能就是 document.scripts