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

请您参考如下方法:

Molle 博士的回答是正确的,但我总是喜欢工作示例。

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"); 

示例页面 => [已删除。请参阅下面的更新]

结果:

注意: 我必须允许演示代码的弹出窗 Eloquent 能工作,但这是另一个 SO 问题的另一个问题。 ; )

更新:

这样做

page.alert() 

之所以有效,是因为它不必等待页面完成加载就可以工作。为了能够调用函数是加载页面上的脚本,您必须确保脚本已完成加载。为了说明这一点,我更改了示例。

示例页面 => 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(); 

控制台输出

打开的页面


评论关闭
IT序号网

微信公众号号:IT虾米 (左侧二维码扫一扫)欢迎添加!