gpt4 book ai didi

javascript - 应用程序后台脚本,访问打开窗口的元素

转载 作者:行者123 更新时间:2023-11-30 16:17:30 25 4
gpt4 key购买 nike

我正在开发 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com