【问题标题】:Send message from background script to content script then response in chrome extension将消息从后台脚本发送到内容脚本,然后在 chrome 扩展中响应
【发布时间】:2015-12-13 07:44:30
【问题描述】:

我正在尝试制作 chrome 扩展。我的后台脚本在用户界面中按下按钮时触发。它应该向我的内容脚本发送一条消息,该脚本会将响应发送回后台脚本。无法完全弄清楚这应该如何工作。单击侦听器正在触发,但消息传递不起作用。这是我到目前为止得到的:

后台脚本:

$(document).on('click', '#getGlobalFuncsBtn', function(){
    chrome.extension.sendMessage({text:"getStuff"},function(reponse){       
        if(reponse.type == "test"){
            console.log('test received');
        }
    });
    console.log('click listener');
});

内容脚本:

chrome.extension.onMessage.addListener(function(message,sender,sendResponse){
    if(message.text == "getStuff"){
        console.log('test sent');
        sendResponse({type:"test"});
    }
});

弹出 HTML:

<!DOCTYPE html>
<html>
<head>
</head>
<body>

<button id="getGlobalFuncsBtn">Get Global Funcs</button>

<script src="jquery-2.0.2.min.js"></script>
<script src="background.js"></script>
</body>
</html>

manifest.json:

{
  "manifest_version": 2,

  "name": "Var Viewer",
  "description": "This extension allows you to view and change all user defined js global vars.",
  "version": "1.1",
  "permissions": [
    "storage"
  ],
  "content_scripts": [
    {
      "matches": ["http://*/*", "https://*/*"],
      "js": ["jquery-2.0.2.min.js","content.js"]
    }
  ],
  "web_accessible_resources": [
    "jquery-2.0.2.min.js"
  ],
  "background": {
    "scripts": ["background.js"],
    "persistent": true
  },
  "browser_action": {
    "default_icon": "icon.png",
    "default_popup": "pop.html",
    "default_title": "Var Viewer"
  }
}

【问题讨论】:

    标签: javascript google-chrome-extension


    【解决方案1】:

    1) 首先,您试图在后台脚本中触发getGlobalFuncsBtn 按钮单击事件,这是没有意义的。实际上,您是在声明 background.js 两次:第一次在 manifest 文件中:

    "background": {
      "scripts": ["jquery-1.7.2.min.js","background.js"]
    },
    

    (表示它是后台脚本)

    ,第二次进入popup.html:

    <script src="background.js"></script>
    

    (表示它是一个弹出式 JavaScript 文件)

    Background page 是您只执行一些后台操作(例如,计算)的地方。 popup.html 是您的实际弹出窗口,因此您应该使用 jQuery 使用按钮。总的来说,您应该只删除 manifest.json 中的 background 字段(最好将 background.js 重命名为 popup.js 之类的名称,但这不是必需的)。

    (您的后台脚本会在按下按钮时触发,因为您已正确声明它一次 - 在 popup.html 内部。)

    您可以在官方文档中阅读更多关于background pages的信息:http://developer.chrome.com/extensions/background_pages.html

    2)您的第二个问题是扩展页面(它可以是任何扩展页面,在您的代码 sn-ps 中为background.js)和content script 之间的消息发送。如果您想在两个常规扩展页面之间设置通信通道,这非常简单。使用chrome.runtime.sendMessagechrome.runtime.onMessage.addListener。但是,如果您想与content script 通信,则必须通过定义要发送消息的特定tab 来使用稍微复杂一点的方法(content script 实际上是作为您在@ 中指定的选项卡代码的一部分执行的987654342@ 文件)。你的代码应该是这样的:

    background.js(或popup.js,如果你重命名它):

    // code below is supposed to be inside your button trigger
    chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
      chrome.tabs.sendMessage(tabs[0].id, {text:"getStuff"}, function(response) {
        if(response.type == "test"){
          console.log('test received');
        }
      });
    });
    

    Content script 事件侦听器对于extension pagecontent script 看起来相同,因此您的content.js 代码应该可以正常工作。你只需要将extension替换为runtime即可:

    content.js:

    chrome.runtime.onMessage.addListener(
      function(request, sender, sendResponse) {
        if (request.text == "getStuff") {
          console.log('test sent');
          sendResponse({type: "test"});
        }
    });
    

    很高兴了解Chrome extension: http://developer.chrome.com/extensions/messaging.html 中传递的消息。

    【讨论】:

    • 我认为你指出的一切都应该是正确的减去一件事。我想我需要在清单文件的 web_accessible_resources 中列出 content.js 。如果它未在其中列出,则不能用作内容脚本。由于这个事实,我已经尝试过 runtime.onMessage 和 tabs.query 之前它从未工作过。感谢您的帮助,尽管我不知道两次注入 bg 脚本。干杯。 :)
    • 我还刚刚发现弹出脚本会被刷新(如果您对其进行更改)只需重新打开弹出窗口(假设您已对其进行更改并将其保存并将其加载为未打包的扩展) ),但内容脚本只能通过重新安装扩展来刷新。 “更新扩展”按钮实际上并没有更新它。
    • @carter 是的,你是对的。 Content script 实际上与扩展分开运行。它比扩展文件更接近标签的代码,因此您需要重新加载扩展以强制应用content script 代码更改。
    猜你喜欢
    • 1970-01-01
    • 2014-11-27
    • 2014-07-16
    • 1970-01-01
    • 1970-01-01
    • 2013-06-27
    • 1970-01-01
    • 2021-10-14
    • 2016-09-09
    相关资源
    最近更新 更多