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:
Note: I had to allow popups for the demo code to work but that is another issue for another SO question. ; )
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
Opened page
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()
精彩评论