【问题标题】:how to send message from backgroundjs to content script in chrome extension?如何将消息从 backgroundjs 发送到 chrome 扩展中的内容脚本?
【发布时间】:2015-11-06 06:42:12
【问题描述】:

我正在开发 chrome 扩展,我一直坚持一个非常具体的部分,假设 backgroundjs 会向当前活动选项卡发送消息。

这是我的清单文件

ma​​nifest.json

{
     "manifest_version": 2,
     "name": "test",
     "description": "Some_Test",
     "version": "1.0",

     "background": {
     "page":  "background.html"
     },
     "content_scripts": [
         {
             "matches": [ "http://*/*", "https://*/*" ],
             "js": [ "content.js" ]
         }
     ],
     "permissions": [
     "background",
     "activeTab",
     "tabs",
     "http://*/*",
     "https://*/*"
     ],
     "browser_action": {
         "default_popup": "popup.html"
      }
}

popup.html

<html>
<body>
    <button id="read-button">Read</button>
    <script type="text/javascript" src="popup.js"></script>
</body>
</html>

popup.js

function readObject(e) {
    console.log(chrome.extension.getBackgroundPage().read());
}

document.getElementById('read-button').addEventListener('click', readObject);

background.html

<!DOCTYPE html>
<html>
    <head>
    </head>
<body>
    <script type="text/javascript" src="background.js"></script>
</body>
</html>

background.js

function read() {
    chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
        chrome.tabs.sendMessage(tabs[0].id, { greeting: "hello" }, function (response) {
            return response.farewell;
        });
    });
}

content.js

chrome.runtime.onMessage.addListener(
  function (request, sender, sendResponse) {
      console.log("hello");
      if (request.greeting == "hello")
          sendResponse({ farewell: "goodbye" });
  });

这是错误所在:

chrome.tabs.sendMessage(tabs[0].id, { greeting: "hello" }, function (response) {
            return response.farewell;
        });

似乎我无法访问 tabs[0] 对象或者我无法理解它返回的数组,因为我想访问活动选项卡,而 tabs[0] 只是意味着它正在获取浏览器中的第一个选项卡而不是活动选项卡。

【问题讨论】:

    标签: javascript google-chrome google-chrome-extension


    【解决方案1】:

    我认为只有当活动窗口是后台页面的开发者工具时才会发生这种情况。

    在测试扩展时切换到普通浏览器窗口或在popup.js中定义read()函数,如果不是绝对需要,则将背景页面完全删除。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-02-04
      • 2017-12-24
      • 2021-11-16
      • 2013-10-12
      • 2014-11-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多