【发布时间】:2011-02-26 04:49:36
【问题描述】:
我正在尝试拦截所有页面对 document.write 的调用。通过注入类似的脚本来设置页面内的拦截
function overrideDocWrite() {
alert("Override called");
document.write = function(w) {
return function(s) {
alert("special dom");
w.call(this, wrapString(s));
};
}(document.write);
alert("Override finished");
}
简单且有效,但我希望我的扩展程序能够从扩展程序内部为每个文档对象设置拦截。我找不到办法做到这一点。我试图监听“加载”事件并在那里设置拦截,但它也失败了。如何将分机的呼叫挂接到doc.write?
我取得了一些进展:
var myExtension = {
init: function() {
var appcontent = document.getElementById("appcontent"); // browser
if (appcontent)
appcontent.addEventListener("DOMContentLoaded", myExtension.onPageLoad,
true);
},
onPageLoad: function(aEvent) {
var doc = aEvent.originalTarget; // doc is document that triggered "onload" event
// do something with the loaded page.
// doc.location is a Location object (see below for a link).
// You can use it to make your code executed on certain pages only.
alert("Override called");
alert(doc);
alert(doc.write);
alert(doc.wrappedJSObject);
alert(doc.wrappedJSObject.write);
doc.wrappedJSObject.write = function(w) {
return function(s) {
alert("special dom");
w.call(this, "(" + s + ")");
};
}(doc.write);
alert("Override finished");
}
}
这似乎有效,但 DOMContentLoaded 是该作业的错误事件,因为它被触发得太晚了!有没有更早的事件可以收听?
【问题讨论】:
-
我想出了一种不同的方法来回避不得不介入 document.write。但这并不意味着它是不可能的:-)
-
其实,我期待覆盖 window.print 但问题是一样的。
标签: javascript firefox-addon document.write