javascript 来自 background.js 的内容脚本中的 Chrome 调用函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18039277/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 10:34:06  来源:igfitidea点击:

Chrome call function in content scripts from background.js

javascriptgoogle-chrome-extension

提问by Lebowski156

I've read the documentation but I still haven't been able to get this working.

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

Here is my manifest:

这是我的清单:

{
    "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"
    }
}

I have a function in content.js called "myFunc". In background.js, I have a function, "myHandler" that is called by a contextMenus.onClicked listener. I want to call myFunc, from myHandler. I tried using tabs.executeScript, and tabs.query, but I can't seem to get the function to be called. Can anyone explain to me how I am supposed to let background.js call a function in content.js?

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

回答by u1841048

To call a function in the content script from the background page, you first need to know the tab id. contextMenus.onClickedevent has a tabparameter containing that id. Then use message passingto do it.

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

For example, in your background page:

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

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

In your content script:

在您的内容脚本中:

chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
    sendResponse(myFunc(request.args));
});