Javascript 在扩展名';中加载带有document.write的脚本;s内容脚本
如果脚本包含:Javascript 在扩展名';中加载带有document.write的脚本;s内容脚本,javascript,google-chrome,dom,google-chrome-extension,content-script,Javascript,Google Chrome,Dom,Google Chrome Extension,Content Script,如果脚本包含: document.write("<iframe>ads here</iframe>"); document.write(“此处的广告”); 如果在请求加载页面之前已将其包含在html中,则其外观可能如下所示: <html> <!-- stuff !--> <div><script src="document_write.js" type="text/javascript"></script>&
document.write("<iframe>ads here</iframe>");
document.write(“此处的广告”);
如果在请求加载页面之前已将其包含在html中,则其外观可能如下所示:
<html>
<!-- stuff !-->
<div><script src="document_write.js" type="text/javascript"></script></div>
<body>
</html>
加载带有类似于上述代码的html页面将导致
被放置在容纳脚本的
标记中。如果在页面加载后调用document.write()
,它将覆盖整个页面
Chrome extensions的内容脚本还将使用文档覆盖页面。写入,或使其崩溃-这取决于页面在生命周期中的调用时间
有没有办法在Chrome的内容脚本中插入包含document.write()
的脚本?在我的ajax站点上使用转换跟踪脚本时,我遇到了同样的问题。我最终覆盖了document.write,解决了这个问题
$(document).ready(function() {
document.write = function(str) {
var moz = !window.opera && !/Apple/.test(navigator.vendor);
if (str.match(/^<\//))
return;
if (!window.opera)
str = str.replace(/&(?![#a-z0-9]+;)/g, "&");
str = str.replace(/<([a-z]+)(.*[^\/])>$/, "<$1$2></$1>");
if (!moz)
str = str.replace(/(<[a-z]+)/g, "$1 xmlns='http://www.w3.org/1999/xhtml'");
var div = document.createElementNS("http://www.w3.org/1999/xhtml", "div");
div.innerHTML = str;
var pos;
if (!moz) {
pos = document.getElementsByTagName("*");
pos = pos[pos.length - 1];
} else {
pos = document;
while (pos.lastChild && pos.lastChild.nodeType == 1)
pos = pos.lastChild;
}
var nodes = div.childNodes;
while (nodes.length)
pos.parentNode.appendChild(nodes[0]);
};
});
$(文档).ready(函数(){
document.write=函数(str){
var moz=!window.opera&!/Apple/.test(navigator.vendor);
if(str.match(/^使用document.write()是否有特殊原因)
在内容脚本中?我不希望这样,但对于第三方脚本,如广告和跟踪器,这是很常见的。您是否尝试过使用内容脚本
属性?我尝试过;我希望插入的JS运行的时间似乎并不能真正解决问题。我无法运行文档。在加载HTML之前使用脚本编写-即使是这样,那也肯定不是我想把结果代码放在的地方,或者类似的地方。对不起,问题是什么,你想达到什么,现在还不清楚。(这可能是因为我在广告、跟踪器等方面的经验很好。)你能解释一下opera和safari测试的目的吗?这是一个通用的覆盖,我从John Resig的博客中得到的[我明白了。博客上说这个解决方案不适用于IE-对于“较新的”IE9+,它仍然适用吗?