如何将消息发送到由backgroundScript

时间:2019-07-30 09:27:51

标签: javascript google-chrome

related question

我想在新窗口中运行chrome扩展程序。 因此,当我单击chrome扩展程序图标时,我通过chrome.windows.create方法创建了chrome.window对象。

<backgroundScript.js>

chrome.browserAction.onClicked.addListener(_ => {
chrome.windows.create({
        url: chrome.runtime.getURL('index.html'),
        type: 'popup',
        width: 300
      }, (_chromeWindow) => {
        chromeWindow = _chromeWindow;
      });
});

现在,我的扩展程序需要与内容脚本进行通信。一个简单的示例情况是,当我在内容(用户正在查看的任何文档)中单击DOM时,我想向扩展内容发送消息。

<contentScript.js>

chrome.runtime.sendMessage({ type: 'DOM is clicked'});

我确实在backgroundScript上收到了它的消息,但是我想不出任何将它的消息发送到我新创建的窗口形式的扩展程序中的方法。

当在backgroundScript收到“单击DOM”消息时,我确实尝试过,我通过使用chrome.tabs.query方法查询选项卡来搜索具有windowId相同的选项卡来创建extensionWindow id。然后,我通过chrome.tabs.sendMessage将消息发送到其已建立的选项卡。奇怪的是,我能够找到它的标签,但以某种方式无法接收消息。(除了已创建的标签,每个标签都能接收消息)

{
  "manifest_version": 2,
  "name": "test extension",
  "short_name": "test extension",
  "version": "1.2.0",
  "description": "test extension",
  "permissions": [
    "tabs",
    "downloads",
    "storage",
    "activeTab",
    "declarativeContent"
  ],
  "browser_action": {
    "default_title": "test extension",
    "default_icon": {
      "16": "assets/images/favicon-16.png",
      "32": "assets/images/favicon-32.png",
      "48": "assets/images/favicon-48.png",
      "128": "assets/images/favicon-128.png"
    }
  },
  "options_ui": {
    "page": "index.html#/option",
    "open_in_tab": false
  },
  "web_accessible_resources": [
    "index.html",
    "content-styles.css"
  ],
  "content_scripts": [
    {
      "js": ["contentPage.js"],
      "matches": ["<all_urls>"],
      "css": ["content-styles.css"]
    }
  ],
  "background": {
    "scripts": ["backgroundPage.js"],
    "persistent": false
  },
  "content_security_policy": "script-src 'self' 'unsafe-eval'; object-src 'self'",
  "icons": {
    "16": "assets/images/favicon-16.png",
    "32": "assets/images/favicon-32.png",
    "48": "assets/images/favicon-48.png",
    "128": "assets/images/favicon-128.png"
  },
  "commands": {
    "toggle-by-keyboard": {
      "suggested_key": {
        "default": "Ctrl+I",
        "windows": "Ctrl+I",
        "mac": "Command+I"
      },
      "description": "Toggle test extension"
    },
    "refresh": {
      "suggested_key": {
        "default": "Ctrl+U",
        "windows": "Ctrl+U",
        "mac": "Command+U"
      },
      "description": "Refresh test extension"
    }
  }
}

这是我的manifest.json,以获取更多信息。

window.onmessage = function(event) { 
  console.log('DOM is clicked', event);
}

并在扩展index.html主javascript文件中监听窗口onmessage事件。

总结一下我的问题,我如何让由chrome.windows.create方法创建的chromeExtension与backgroundScript通信?

0 个答案:

没有答案