简体   繁体   English

如何避免在外部脚本中使用 document.write

[英]How to avoid document.write in an external script

I want to avoid or replace the document.write loading through an external script.我想避免或替换通过外部脚本加载的 document.write。 here the link //lv.adocean.pl/files/js/aomini.js这里的链接//lv.adocean.pl/files/js/aomini.js

I tried this (answered by someone) but it didn't help.我试过这个(有人回答),但没有帮助。

document.write=function(s){
    var scripts = document.getElementsByTagName('script');
    var lastScript = scripts[scripts.length-1];
    lastScript.insertAdjacentHTML("beforebegin", s);
}

Any idea?任何的想法?

I will try to explain @freedomm-m's suggestion, hoping to be clear.我会尽量解释@freedomm-m 的建议,希望能说清楚。

To re-assign document.write , which returns a function, to an "empty function" ... could do the trick to avoid the "normal" execution of document.write .将返回函数的document.write重新分配给“空函数” ……可以避免“正常”执行document.write

By "empty function" , I mean a totally valid function, but doing strictly nothing.通过“空函数” ,我的意思是一个完全有效的函数,但严格来说什么都不做。

So after that re-assignment, every times the document.write function will be called anywhere in the document, instead of executing the write function found under the document object's property, it will execute that "empty function" (read: Nothing).所以在重新赋值之后,每次document.write函数都会在文档的任何地方被调用,而不是执行在document对象的属性下找到的write函数,它会执行那个“空函数” (读取:Nothing)。

Here is a demo of that principle applyed on the console.log function, just to keep it simple and be obvious in this demo here.这是应用于console.log函数的该原则的演示,只是为了保持简单,并在此演示中显而易见。

 console.log("I am executing...") console.log("I am executing too...") // Assing an empty function console.log = function(){} console.log("I am NOT executing!") console.log("I feel useless now... :( ")

Now to "temporarly" avoid a function execution, you have to store it in another variable in order to "undo" the re-assigment...现在要“暂时”避免函数执行,您必须将其存储在另一个变量中以“撤消”重新分配...

 console.log("I am executing...") console.log("I am executing too...") // Assign the function to a variable let tempStorageOfTheDisabledFunction = console.log // Assing an empty function console.log = function(){} console.log("I am NOT executing!") console.log("I feel useless... :( ") // Restore the original function console.log = tempStorageOfTheDisabledFunction console.log("Yeah! I'm back in play!") console.log("I feel better.")

So now, what fredomm-m suggested to try is:所以现在,fredomm-m 建议尝试的是:

<script>document.write = function(){}</script>
<script src="path-to-external-js"></script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM