Chrome扩展程序:标签上的executeScript

时间:2014-10-21 16:12:51

标签: 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(15, false);"
});

上面的代码应该更新选项卡,将其设置为活动状态,然后尝试执行名为messageOpen()的函数。我遇到的问题是,messageOpen()函数作为一个函数存在,该函数包含在我网站的<HEAD>中,但不是我的扩展程序。

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

Uncaught ReferenceError: messageOpen is not defined

我100%肯定messageOpen()功能如果我定期浏览网站,但使用executeScript时,就好像扩展无法运行已加载的功能我的活动标签。

有人有一些建议或选择吗?

1 个答案:

答案 0 :(得分:2)

这是因为内容脚本无法与注入的页面的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);"
});
相关问题