Javascript Chrome扩展:选项卡上的executeScript

Javascript Chrome扩展:选项卡上的executeScript,javascript,google-chrome,google-chrome-extension,Javascript,Google Chrome,Google Chrome Extension,我最近开始开发我的第一个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

我最近开始开发我的第一个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()
作为一个函数存在于我的网站的
中,但不是我的扩展名

因此,当尝试执行
messageOpen()
函数时,我收到以下错误:

Uncaught ReferenceError: messageOpen is not defined
如果我定期浏览网站,
messageOpen()
函数可以正常工作,我100%肯定这一点,但是当使用
executeScript
时,就好像扩展无法运行已经在我的活动选项卡中加载的函数一样


有人有什么建议或选择吗?

这是因为内容脚本无法与它们注入到的页面的
窗口
对象交互。如果要执行使用
messageOpen()
函数的脚本,则必须使用
将该代码注入页面上下文,如下所示:

var myScript = document.createElement('script');
myScript.textContent = 'messageOpen(15, false);';
document.head.appendChild(myScript);
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);"
});
因此,如果您想使用
executeScript()
方法和
“code”
属性插入此代码,您可以这样做:

var myScript = document.createElement('script');
myScript.textContent = 'messageOpen(15, false);';
document.head.appendChild(myScript);
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);"
});

非常感谢你,马可,这正是我需要的。