【问题标题】:Trying to send a message from a html window that is in the extension package to the content script尝试从扩展包中的 html 窗口向内容脚本发送消息
【发布时间】:2019-08-04 17:22:36
【问题描述】:

我添加了一个新的(弹出窗口)window

不是您在清单中注册的 popup.html。

用户将信息放在窗口中,当他们单击按钮时,需要将信息发送到 content.js 脚本。

(弹出)窗口的 html 在扩展包中,因此无需在 manifest.json 中添加“externally_connectable”对象 而且它不是另一个扩展的一部分,所以你不要使用 sendMessageExternal 方法。

Manifest.json

    {
"name": "extension name",
"version": "0.1",
"options_page": "settings.html",
"manifest_version": 2,
"background": {
    "scripts": ["background.js"],
    "persistent": false
},
"content_scripts": [
    {
        "matches": ["<all_urls>"],
        "js":["jquery.min.js", "content.js"]
    }
],
"browser_action": {
    "default_popup": "popup.html",
    "default_title": "Default title",
    "default_icon": {
        "16": "images/logo16.png",
        "32": "images/logo32.png",
        "48": "images/logo48.png",
        "128": "images/logo128.png"
    }
},
"icons": {
    "16": "images/logo16.png",
    "32": "images/logo32.png",
    "48": "images/logo48.png",
    "128": "images/logo128.png"
        }
    }

内容.js

    chrome.runtime.onMessage.addListener(function(req, sender, senderres){
            if(req.succes == true){
            // Do stuff...
        }
    });

在(弹出)窗口中引用的js文件

  window.onload = function(){
    document.getElementById("BtnFinish").addEventListener('click',
    function(){
      chrome.runtime.sendMessage({succes: true});
      self.close();
    });
  }

这是我在 background.js 中用来创建(弹出)窗口的代码

    chrome.windows.create({
        url: chrome.runtime.getURL("form.html"),
        type: "popup"
    });

我确实收到了任何错误消息。 该按钮可以激活每一段代码,但 content.js 没有收到任何内容。

如果您需要更多信息或我忘记了什么,请随时询问。

【问题讨论】:

    标签: javascript google-chrome-extension


    【解决方案1】:

    如果你看一下documentation,里面有一个子句:

    请注意,扩展无法使用此方法向内容脚本发送消息。要将消息发送到内容脚本,请使用 tabs.sendMessage。

    这意味着你必须这样做:

    chrome.windows.getAll({populate:true}, (windows) => {
      windows.forEach((window) => {
        window.tabs.forEach((tab) => {
          chrome.tabs.sendMessage(tab.id, {succes: true});
        });
      });
    });
    

    您需要tabs 权限才能执行此操作。 我正在使用chrome.windows.getAll,因为您似乎正在尝试向另一个窗口中的内容脚本发送消息,而不是同一窗口的不同选项卡。

    【讨论】:

      猜你喜欢
      • 2014-02-04
      • 2017-12-24
      • 2013-10-12
      • 1970-01-01
      • 1970-01-01
      • 2011-08-31
      • 1970-01-01
      • 2020-10-12
      • 1970-01-01
      相关资源
      最近更新 更多