Accessing document's javascript variable from firefox extension

后端 未结 3 1806
孤城傲影
孤城傲影 2020-12-10 05:26

is it possible for Firefox extension (toolbar) to access document\'s variables? detailed explanation follows..

loaded document:



        
相关标签:
3条回答
  • 2020-12-10 06:02

    not so hard :)

    in extension:

    var jso=window.content.document.defaultView.wrappedJSObject;
    

    now you can access any function or global variable in the webpage from the extension:

    alert(jso.pagevar);
    
    jso.pagefunction("hey");
    
    0 讨论(0)
  • 2020-12-10 06:07

    Yes, accessing a JS variable in content is and always was possible. Doing this the naive way wasn't safe (in the sense that a malicious web page could get chrome privileges) in older Firefox versions.

    1) If you control the web page and want to pass information to the extension, you should indeed use the events technique. This worked and was/is safe in all Firefox versions.

    2) If you want to read a value from the content document, you can just bypass the XPCNativeWrapper:

    var win = window.top.getBrowser().selectedBrowser.contentWindow;
    // By the way, this could just be
    //   var win = content;
    // or 
    //   var win = gBrowser.contentWindow;
    alert(win.variableForExtension); // undefined
    win.wrappedJSObject.variableForExtension // voila!
    

    This was unsafe prior to Firefox 3. In Firefox 3 and later it is OK to use, you get another kind of wrapper (XPCSafeJSObjectWrapper), which looks the same as the object from the content page to your code, but ensures the content page won't be able to do anything malicious.

    3) If you need to call a function in a content web page or run your own code in the page's context, it's more complicated. It was asked and answered elsewhere many times, but unfortunately never documented fully. Since this is unrelated to your question, I won't go into the details.

    0 讨论(0)
  • 2020-12-10 06:08

    If you are working with the new High-Level SDKs then accessing the variable via content scripts is a little different. You can't access the JavaScript objects directly from the add on code, but you can reach them from content scripts that have been attached to an open page via the unsafeWindow object. For example:

    require("sdk/tabs").open({
      url: 'http://www.example.com/some/page/',
      onOpen: function(tab) {
        var worker = tab.attach({
          contentScript: 'unsafeWindow.variableForExtension = 1000;'
        });
      }
    });
    

    To read the variables you'll need to use the port methods on the worker variable as described in Mozilla's content script article.

    Note that there are some security restrictions when dealing with objects and functions. See the articles for details.

    0 讨论(0)
提交回复
热议问题