Search code examples
javascriptfirefoxfirefox-addonsidebar

How to let a sidebar execute javascript code from the main document?


I'm working on a firefox sidebar that loads a webpage in the main document. Now i'd like to call a javascript function from the main document in response of a pushed button on the sidebar. How can the sidebar cause the main document to execute one of its javascript functions? So far, I'm having a variable containing the javascript code, but how can it be executed? (in the context of the loaded website?)


Solution

  • Dr.Molle is correct with his answer but I always love working examples.

    console.log("Opening new page at http://example.com");
    page = window.open('http://example.com');
    console.log(page);
    console.log("calling alert on opened page");
    page.alert("I opened and the previous windows JS called me!!!!");
    console.log("called alert");
    

    Example page => [Removed. See update below]

    Results:

    alert initiated from other page console logs

    Note: I had to allow popups for the demo code to work but that is another issue for another SO question. ; )

    firefox popup blocked notice

    UPDATE:

    So doing

    page.alert()
    

    worked because it didn't have to wait for the page to finish loading for it to work. In order to be able to call a function is a script on the loaded page you have to ensure that the script has finished loading. To do illustrate this I changed my example.

    Example page => http://mikegrace.s3.amazonaws.com/forums/stack-overflow/example-call-function-in-opened-page.html

    The JS looks like this

    page = window.open('http://mikegrace.s3.amazonaws.com/forums/stack-overflow/example-the-other-page.html');
    
    var initOtherPage = function() {
      try {
        page.showMeTheMoney();
        console.log("It worked!");
      } catch (e) {
        console.log("failed to call function on other page because: "+e);
        setTimeout(function() {
          console.log("trying again")
          initOtherPage();
        }, 1000);
      }
    }
    initOtherPage();
    

    Console output

    alt text

    Opened page

    alt text