以下注入(inject)在 Chrome 中完美运行,但是在最新的 Firefox(版本 21)中,文档永远保持“正在连接...”,甚至没有像 <img>
这样的元素。负载。 (但如果你点击重新加载它们,它们就会显示正常......)
截图:
脚本:
// ==UserScript==
// @name Test
// @namespace Test
// @author Owyn
// @match http://*
// ==/UserScript==
function inject(func) {
var source = func.toString();
var script = document.createElement('script');
script.innerHTML = "("+ source +")()";
document.body.appendChild(script);
}
function myf() {
document.write('<html>TEST</html>');
}
inject(myf);
任何修复,任何解决方法?我应该就错误联系 Mozilla 吗?
附言- 我使用 document.write 删除所有事件监听器(我不知道)并且还没有找到替代方法。
最佳答案
最聪明/最好(最好)的做法是避免 document.write()
。 使用 DOM 技术。这是完整的脚本:
// ==UserScript==
// @name _Replace a target page using DOM techniques
// @include http://YOUR_SERVER.COM/YOUR_PATH/*
// @grant GM_addStyle
// ==/UserScript==
/*- The @grant directive is needed to work around a design change
introduced in GM 1.0. It restores the sandbox.
*/
var D = document;
var newDoc = D.implementation.createHTMLDocument ("");
D.replaceChild (
D.importNode (newDoc.documentElement, true),
D.documentElement
);
D.body.innerHTML = '<h1>TEST</h1>'
Greasemonkey 通常在 DOMContentLoaded
上触发,不会 在页面完全加载完成时触发。默认情况下,Chrome 会晚于此触发。
无论如何,在 DOMContentLoaded
,在 Firefox 中;当您删除当前文档时,某些内容会变得孤立。因此,“悸动者”永远不会停止,并且可能会错过其他一些清理工作。
这可能是一个错误,但无论如何您都不应该使用 document.write()
。此外,根据 the DOC , 你应该调用 document.close()
一个肮脏的解决方法是等到页面加载后再触发。因此,与其直接调用 inject(myf);
,不如这样调用:
function myf () {
document.write ('<html>TEST</html>');
document.close ();
}
window.addEventListener ("load", function () { inject(myf); }, false);
但改用 DOM 方法!它们会更快,并且不会遇到极端情况的错误和安全违规。
关于javascript - 从 Greasemonkey 脚本注入(inject) document.write 调用不会导致任何加载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16893197/