How to override JavaScript function from a Firefox extension?

风流意气都作罢 提交于 2019-12-05 13:06:05

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);

The same goes for document with the event document-element-inserted as of gecko 2.0 .

JavaScript uses a prototypical inheritance system, instead of having classes, objects have prototypes. Prototypes are real objects that are used as a reference to other objects for inheritance of methods and attributes.

The best strategy would be to override the method write in the prototype of "document" (which for the HTML document is HTMLDocument). This should effectively wrap the method for all instances of "document" inside the pages loaded in the browser since they all use the same prototype.

Instead of

document.write = function() { ... }

try something like this:

HTMLDocument.prototype.write= function() { ... }

UPDATE: It does not seem to be as easy as I initially thought, this does not seem to work at first try.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!