Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
837 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 Answer

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
        }
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...