我最近开始开发我的第一个Google Chrome扩展程序,但遇到的问题是我不确定如何解决。
在我的脚本中,我正在检查是否向特定网站打开了选项卡,如果是,则正在执行以下代码:
chrome.tabs.update(tab.id, {active: true});
// Execute code on the existing tab to open the Message.
chrome.tabs.executeScript(tab.id, {
"code": "messageOpen(15, false);"
});
上面的代码应将选项卡更新为活动状态,然后尝试执行一个名为的函数messageOpen()
。我遇到的问题是该功能messageOpen()
作为<HEAD>
我网站的,而不是我的扩展名中包含的功能存在。
因此,在尝试执行messageOpen()
功能时,我收到此错误:
Uncaught ReferenceError: messageOpen is not defined
我100%肯定messageOpen()
如果我定期浏览网站可以使用该功能,但是使用时executeScript
,似乎该扩展程序无法运行已经在我的活动标签中加载的功能。
有人有什么建议或替代方法吗?
发生这种情况是因为内容脚本无法与其window
被注入到的页面对象进行交互。如果要执行使用messageOpen()
函数的脚本,则必须使用将该代码注入到页面上下文中<script>
,如下所示:
var myScript = document.createElement('script');
myScript.textContent = 'messageOpen(15, false);';
document.head.appendChild(myScript);
因此,如果您想使用executeScript()
方法和"code"
属性注入此代码,可以这样进行:
chrome.tabs.update(tab.id, {active: true});
// Execute code on the existing tab to open the Message.
chrome.tabs.executeScript(tab.id, {
"code": "var myScript = document.createElement('script');"
+ "myScript.textContent = 'messageOpen(15, false);';"
+ "document.head.appendChild(myScript);"
});
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句