且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在执行脚本元素之前将其删除?

更新时间:2022-06-25 23:36:51

删除脚本元素不会执行任何操作.如果您可以某种方式访问​​脚本元素,则该脚本元素已执行很久了,将其删除将无效.

Removing a script element does not do anything. If you can somehow access a script element, it was executed a long time ago and removing it will have no effect.

所以我们需要解决它.如果您的脚本元素位于页面顶部,例如:

So we need to work around it. If your script element is at the top of the page like this:

<head>
    <script src="yourscript.js"></script>

您可以向同一页面发出同步ajax请求,因此您可以将其内容解析到新文档中,修改所有脚本标签,然后替换 当前文档以及修改后的文档.

You could make a synchronous ajax request to the same page, so you can parse its content into a new document, modify all script tags and then replace the current document with the modified document.

var xhr = new XMLHttpRequest,
    content,
    doc,
    scripts;

xhr.open( "GET", document.URL, false );
xhr.send(null);
content = xhr.responseText;

doc = document.implementation.createHTMLDocument(""+(document.title || ""));

doc.open();
doc.write(content);
doc.close();


scripts = doc.getElementsByTagName("script");
//Modify scripts as you please
[].forEach.call( scripts, function( script ) {
    script.removeAttribute("src");
    script.innerHTML = 'alert("hello world");';
});

//Doing this will activate all the modified scripts and the "old page" will be gone as the document is replaced
document.replaceChild( document.importNode(doc.documentElement, true), document.documentElement);

不幸的是,这不能在jsfiddle或jsbin中设置.但是您应该能够完全复制粘贴此代码并将其原样粘贴到此代码中 谷歌浏览器中的页面控制台.您应该看到警报,并且当您检查直播时,每个脚本都已修改.

Unfortunately this cannot be set up in jsfiddle or jsbin. But you should be able to copy paste this code exactly as it is into this page's console in google chrome. You should see the alerts and when you inspect the live dom, each script was modified.

区别在于我们是在页面上执行脚本后运行此程序,因此旧脚本仍应在页面上起作用. 这就是为什么要使其正常工作,您需要成为页面上第一个执行此操作的脚本.

The difference is that we are running this after scripts have been executed on the page, so the old scripts should still have a working effect on the page. That's why, for this to work, you need to be the very first script on the page to do it.

经过测试可在Google Chrome中使用. Firefox由于某些原因完全忽略了doc.write调用.

Tested to work in google chrome. Firefox is completely ignoring the doc.write call for some reason.