我想收集所有<script> ....</script>
代码段出现在 HTML 页面中的一些变量中。
执行此操作的更简单方法应该是什么,知道如何使用 JavaScript 检索它吗??
任何帮助将不胜感激。
最佳答案
获取您可以使用的脚本列表
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
});
<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>
关于javascript - 如何在变量中收集HTML页面的所有脚本标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11078654/