我尝试使用 JavaScript 获取脚本标签的 innerHtml。
var scripts = document.getElementsByTagName("script");
console.log(scripts.length);
console.log(scripts[0].innerHtml);
此脚本记录2
and undefined
,但是为什么找到 2 个脚本时返回 undefined ?我需要获取脚本的 innerHtml。任何帮助将不胜感激:)
编辑:
更改innerHtml
为innerHTML
它后仍然会在控制台中引发错误:
Uncaught TypeError: Cannot read property 'innerHTML' of undefined (line 34)
第 34 行是这样的:
var scripts = document.getElementsByTagName("script"); //line 32
for (var i = 0, imax = scripts.length; i < imax; i++) { //line 33
var scriptstring = scripts[i].innerHTML; } // line 34
顺便说一句,该脚本不是嵌入的 .js 文件,而是硬编码在 .html 文件中
编辑 2:整个 .html 文件
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Test</title>
<script type="text/javascript">
onmousemove = function test1() {
window.alert('hello');
}
</script>
<script>
window.onload = function() {
var scripts = document.getElementsByTagName("script");
for (var i = 0, imax = scripts.length; i < imax; i++) {
var scriptstring = scripts[i].innerHTML;
scriptstring = scriptstring.replace(/(\r\n|\n|\r)/gm,""); //convert the innerHTML to one line, easier to match
if (scriptstring.match(/.*(function) (test1).*/) != null) {
scripts[i].parentNode.removeChild(scripts[i]);
}
}
}
</script>
</head>
<body>
</body>
</html>