Javascript 如何在一个变量中收集 HTML 页面的所有脚本标签
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11078654/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to collect all script tags of HTML page in a variable
提问by Ashish Mittal
I would like to collect all the <script> ....</script>
code section present in the HTML page in some variable.
我想<script> ....</script>
在某个变量中收集HTML 页面中存在的所有代码部分。
What should be the simpler way to do this, Any idea how it can be retrieved using JavaScript.??
什么应该是更简单的方法来做到这一点,知道如何使用 JavaScript 检索它。??
Any help will be greatly appreciated.
任何帮助将不胜感激。
回答by mplungjan
To get a list of scripts you can use
要获取您可以使用的脚本列表
document.getElementsByTagName("script");
by tagdocument.scripts;
Built-in collectiondocument.querySelectorAll("script");
by selector$("script")
jQuery by selector
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>
回答by Esailija
The simplest way is probably document.scripts
最简单的方法大概是 document.scripts
回答by Raab
try this
尝试这个
var scripts = document.getElementsByTagName("script");
回答by Sarfraz
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.
现在scripts
是一个 NodeList(就像一个数组),你可以使用scripts[0]
,scripts[1]
等等来访问每一个。
回答by jbrtrnd
Without jQuery :
没有 jQuery :
var scripts = document.getElementsByTagName("script");
With jQuery :
使用 jQuery :
var scripts = $("script");
回答by javascript-noob
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);
}
})();