如何从Firefox扩展中覆盖JavaScript函数? [英] How to override JavaScript function from a Firefox extension?
问题描述
我正在尝试拦截对所有页面的document.write调用。通过注入脚本来设置页面内的拦截,如
I am trying to intercept calls to document.write for all pages. Setting up the interception inside the page by injecting a script like
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
的调用?
Is easy and works, but I would like my extension to setup the interception for each document object from inside the extension. I couldn't find a way to do this. I tried to listen for the "load" event and set up the interception there but it also fails. How do I hook calls to doc.write
from an extension?
我取得了一些进展:
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是错误的事件因为工作太晚了!是否有较早的事件要听?
This seem to work, but DOMContentLoaded is the wrong event for the job, because it is fired too late! Is there an earlier event to listen to?
推荐答案
问题的重新确定!我得到了答案。以下是示例代码:
Ressurection of the question ! I got the answer. Here is a sample code :
const os = Components.classes["@mozilla.org/observer-service;1"].getService(Components.interfaces.nsIObserverService);
os.addObserver({
observe : function(aWindow, aTopic, aData) {
if (aWindow instanceof Ci.nsIDOMWindow && aTopic == 'content-document-global-created') {
aWindow.wrappedJSObject.myfunction = function(){
// Do some stuff . . .
}
}
}
}, 'content-document-global-created', false);
从gecko 2.0开始插入事件document-element的文档也是如此。
The same goes for document with the event document-element-inserted as of gecko 2.0 .
这篇关于如何从Firefox扩展中覆盖JavaScript函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!