Friday, December 3, 2010

Firefox Extension and Web Page Script Execution

To access Web page Document from Extension
  webpageDocument = top.window.content.document;

To Execute Web Page defined function from Firefox Extension

 var wm = Components.classes[';1'].getService(Components.interfaces.nsIWindowMediator);

    var currentWindow = wm.getMostRecentWindow('navigator:browser').getBrowser().contentWindow;
    var sandbox = new Components.utils.Sandbox(SandboxURL);
    // __.proto__  hack removes need of using window.a, window.alert()
    sandbox.__proto__ = currentWindow.wrappedJSObject;
    //  assume web page script defines variable "a"
    var pageResult = Components.utils.evalInSandbox("alert(a);", sandbox);
    dump("\n\n Web  page Function execution Result = " + pageResult);

In FF Extension to execute a Script in a Sandbox and allowing Extension function to be accessed by Sandbox object
Following code I also added to MDN [1].

 // Chrome (FF Extension) custom Functions:
function sandboxAlert(msg){
    dump("\n Inside sandboxAlert");
    msg = XPCSafeJSObjectWrapper(msg);
    dump("\n msg = " + msg);

// variable declared in Chrome code
var tempval = 10;

function sandboxFun1(){
    return tempval;

    // Chrome (Firefox Extension) code

    // create sandbox enviornment to execute script.
    // SandboxURL is required for XHR requests. Same domain are allowed.
    var sandbox = new Components.utils.Sandbox(SandboxURL);

    sandbox.y = 5;  // insert property 'y' with value 5 into global scope.
    var scriptText = "var x = 2 + sandboxFun1(); var k = y + 15; sandboxAlert('Testing'); x + 3";

    // // include chrome function into sandbox context.

    // // execute script into sandbox object
    var sandboxResult = Components.utils.evalInSandbox(scriptText, sandbox);

1. Mozilla FF Extension evalInSandbox


  1. Hello there I am so delighted I found your blog page, I really found you by mistake, while I was researching for something else,
    Regardless I am here now and would just like to say many thanks for a remarkable post and a all round enjoyable blog.Please do keep up the excellent work.
    industrial training indore

  2. It is really a nice and helpful piece of info. I’m glad that you simply shared this helpful info with us. Please keep us
    informed like this. Thank you for sharing.
    mobile application development