应用程序后台脚本,访问已打开的元素 window

App background script, accessing elements of opened window

我正在开发一个 Chrome 应用程序,我需要后台脚本来访问它创建的 html window 的元素。

请不要回答我可以通过创建的window启动的其他脚本来完成,因为这不是我需要的。

这是我的 background.js 文件:

chrome.app.runtime.onLaunched.addListener(function() {
   chrome.app.window.create('window.html',
      {'outerBounds': {'width': 600, 'height': 500 }},
      function(myWin) {
          myWin.contentWindow.document.getElementById('areaId').value='New text!';
   }); 
});

这是windows.html:

<!DOCTYPE html>
<html>
  <head>
  </head>
  <body>
    <textarea id="areaId" name="areaId"  rows="4" cols="50">
      This is my text.
    </textarea>
  </body>
</html>

当我启动应用程序时,出现错误:

"Uncaught TypeError: Cannot set property 'value' of null"

我也试过 myWin.document.getElementById(...) 并用 var myWin=window.open(...) 打开 window 但没有成功。

所以我的问题是,如何从后台脚本访问新创建的 window 的元素?

好的,所以这里发生的是错误的时机。

create的回调在页面的DOM结构构建之前执行;因此,getElementById('areaId') .

没有找到任何东西

您可以尝试挂钩 DOMContentLoaded 事件。

或者,您可以转到 recommended route 并在该回调中定义一些 functions/variables,然后打开的 window 中的代码可以使用(文档推荐 onload) .