12

我已经阅读了文档,但我仍然无法使其正常工作。

这是我的清单:

{
    "name":"app",
    "version":"0.1",
    "manifest_version":2,
    "description":"app",
    "background":{
        "scripts":[
            "scripts/modernizr.min.js", 
            "scripts/background.js"
            ],
        "persistent": false
    },
    "content_scripts": [
      {
        "matches": ["https://*/*", "http://*/*"],
        "js": ["scripts/content.js"],
        "run_at": "document_end"
      }
    ],
    "permissions":[
        "contextMenus", 
        "tabs",
        "http://*/*",
        "https://*/*"
        ],
    "icons":{
        "16":"images/icon_16.png",
        "128":"images/icon_128.png"
    }
}

我在 content.js 中有一个名为“myFunc”的函数。在 background.js 中,我有一个由 contextMenus.onClicked 侦听器调用的函数“myHandler”。我想从 myHandler 调用 myFunc。我尝试使用 tabs.executeScript 和 tabs.query,但似乎无法调用该函数。谁能向我解释我应该如何让 background.js 调用 content.js 中的函数?

4

1 回答 1

14

要从后台页面调用内容脚本中的函数,首先需要知道标签 ID。contextMenus.onClickedevent 有一个tab包含该 id 的参数。然后使用消息传递来做到这一点。

例如,在您的背景页面中:

chrome.contextMenus.onClicked.addListener(function(info, tab) {
  if (tab)
    chrome.tabs.sendMessage(tab.id, {args: ...}, function(response) {
      // ...
    });
});

在您的内容脚本中:

chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
    sendResponse(myFunc(request.args));
});
于 2013-08-04T03:10:58.583 回答