开发者

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

开发者 https://www.devze.com 2023-01-28 11:37 出处:网络
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 butto开发者_如何学编程n on the s

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 butto开发者_如何学编程n 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?)


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:

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

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

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

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

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

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

Opened page

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


Load the page using window.open() and save it into a variable:

page=window.open('some.htm')

then you can access the window using this variable and call functions inside:

page.someFunction()
0

精彩评论

暂无评论...
验证码 换一张
取 消