如何让侧边栏从主文档中执行javascript代码?

Nan*_*ada 2 javascript firefox sidebar firefox-addon

我正在使用firefox侧边栏加载主文档中的网页.现在我想从主文档中调用javascript函数来响应侧栏上的按钮.侧边栏如何导致主文档执行其中一个javascript函数?到目前为止,我有一个包含javascript代码的变量,但它如何执行?(在加载网站的上下文中?)

Mik*_*ace 7

莫尔博士对他的回答是正确的,但我总是喜欢工作的例子.

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");
Run Code Online (Sandbox Code Playgroud)

示例页面=> [已删除.见下面的更新]

结果:

从其他页面发起的警报 控制台日志

注意: 我必须允许弹出窗口才能使用演示代码,但这是另一个问题的另一个问题.; )

firefox弹出窗口阻止通知

更新:

这样做

page.alert()
Run Code Online (Sandbox Code Playgroud)

之所以有效,是因为它不必等待页面完成加载才能正常工作.为了能够调用函数是加载页面上的脚本,您必须确保脚本已完成加载.为了说明这一点,我改变了我的榜样.

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

JS看起来像这样

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();
Run Code Online (Sandbox Code Playgroud)

控制台输出

替代文字

打开的页面

替代文字