Search code examples
javascriptfirefoxfirefox-addonxulsidebar

Firefox sidebar calling javascript functions in main browser window


I'm trying to put together a quick Firefox sidebar for internal use only.

I'm struggling a bit in understanding how sidebar and main browser window communicate. What I want to do exactly is call existing javascript functions that reside in the main browser window only.

My code looks like this;

ff-sidebar.xul

<checkbox label="Button hover" checked="false" oncommand="add_enhance(this)"/>

ff-sidebar.js

function add_enhance(cb){
    if (cb.checked) {
        // this bit is wrong I know
        window.content.document.NEWSTYLE.buttonHover();
    }
}

So the question is, how do I call a function called NEWSTYLE.buttonHover() that lives in the main window?


Solution

  • Theoretically, this should work:

    window.content.NEWSTYLE.buttonHover();
    

    window.content points to the browser content window and the variable NEWSTYLE is defined on this window. In reality things are a bit more messy due to security mechanisms - privileged code cannot access objects of unprivileged code directly. Instead you get to access them through XPCNativeWrapper (see https://developer.mozilla.org/en/XPCNativeWrapper). Technical details changed somewhat in Firefox 4 but essentially it is still the same.

    The easiest way to do what you want without introducing security issues is changing the location of the content window to a javascript: URL. Like this:

    window.content.location.href = "javascript:void NEWSTYLE.buttonHover()";
    

    You won't be able to get the result of this function but it doesn't look like you need it.