我正在开发 Chrome 应用程序,我需要后台脚本来访问它创建的 html 窗口的元素。
请不要回答我可以从创建的窗口启动的其他脚本来完成,因为这不是我需要的。
这是我的 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(...)
打开窗口
但没有成功。
所以我的问题是,如何从后台脚本访问新创建的窗口的元素?
最佳答案
好吧,所以这里发生的是错误的时机。
create
的回调在页面DOM结构构建之前执行;因此,getElementById('areaId')
还没有找到任何东西。
您可以尝试挂接到 DOMContentLoaded
事件。
或者,您可以转到 recommended route并在该回调中定义一些函数/变量,打开的窗口中的代码随后可以使用(文档推荐 onload
)。
关于javascript - 应用程序后台脚本,访问打开窗口的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35268402/