Search code examples
javascriptbrowserxulxulrunner

Call a javascript function which is defined / linked in a (xul) browser element


I'm developing a XUL application which includes a browser element. This browser element is of type="content", so it is not possible to access the XUL elements with JavaScript from within the browser. That's not just ok, but it has to be this way.

My problem is now that I can't access the functions which are defined in the browser element from the XUL elements.

Is there any way I can call a function which is defined or linked in the browser element?


Solution

  • As you already noted, not being able to access content directly is a security feature. If you only want to call a function but aren't interested in the return value then the most simple and secure approach would be to load a javascript: URL into that browser:

    myBrowser.contentWindow.location.href = "javascript:void someFunction()";
    

    If you need to get data back then doing this securely is complicated (anything involving wrappedJSObject is inherently insecure). It is probably best to use the message manager. You can load a content script into the browser (untested, merely exemplifying the point):

    myBrowser.messageManager.loadFrameScript("chrome://.../contentScript.js", false);
    myBrowser.messageManager.addMessageListener("result", function(name, sync, data)
    {
      alert("Got response from content script: " + data);
    });
    

    And contentScript.js would look like this:

    var result = someFunction();
    sendAsyncMessage("result", result);
    

    Note that contentScript.js has content privileges meaning that exploiting it won't give the web page anything. And the data it sends will be converted to JSON and back on the other side, nothing "malicious" can pass.