Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
839 views
in Technique[技术] by (71.8m points)

javascript - Set an object in a page's window object from a Firefox extension?

I want my Firefox extension to add an object to the content window of the browsed page. I want it to have the same effect as running:

top.myobj = {val : 3};

inside a script element in the page.

Any ideas?

I don't think there is a security risk here as I only add an object with a single integer property. Is there a simple way to get the content window object from within the extension code?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

use

var mainWindow = window
    .QueryInterface(Components.interfaces.nsIInterfaceRequestor)
    .getInterface(Components.interfaces.nsIWebNavigation)
    .QueryInterface(Components.interfaces.nsIDocShellTreeItem).rootTreeItem
    .QueryInterface(Components.interfaces.nsIInterfaceRequestor)
    .getInterface(Components.interfaces.nsIDOMWindow);

mainWindow.getBrowser().addEventListener("DOMContentLoaded",
                        youreventhandler, true);

function youreventhandler(event) {
    if (event.originalTarget instanceof HTMLDocument) {

        var doc = event.originalTarget;
        //doc = the document in the just loaded window

        var win = doc.defaultView;

        // if it's just a frame element, then return and wait for the   
        // main event to fire.
        if (win.frameElement)
            return;
        else {
            win.myobj = { val: 3};
            //your other code here
        }
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...