从后台脚本传递给内容脚本Chrome扩展的消息不工作(Chrome extension messag

2019-11-04 05:23发布

我想铬插件的创建消息传递 。 我的代码如下:

manifest.json的:

{
    "name": "Sending Messages Test",
    "version": "1.0",
    "manifest_version": 2,
    "description": "Send a Message to background.js from contentscript.js and send reply",
    "background": {
        "scripts": ["background.js"],
        "persistent": false
    },
    "browser_action": {
        "default_title": "That's the tool tip",
        "default_popup": "popup.html"
    },
    // "permissions": ["tabs"],
    "content_scripts": [{
        "matches": ["http://*/*", "https://*/*"],
        "js": ["contentscript.js"]
    }]
}

popup.html:

<script type="text/javascript" src="popup.js"></script>
<div style="width:200px">
    <button id="button">Color all the divs</button>
</div>

popup.js:

window.onload = function() {
  document.getElementById("button").onclick = function() {
    // alert("in popup.js");
    chrome.extension.sendMessage({
      message: "coming from popup"
    });
  }
}

contentscript.js

chrome.runtime.onMessage.addListener( function(request, sender) {
    alert("Contentscript has received a message from from background script: '" + request.message + "'");
    return true;
});

background.js:

var backgroundScriptMessage = " purple monkey dishwasher";

chrome.extension.onMessage.addListener(function(request, sender) {
    alert("Background script has received a message from contentscript:'" + request.message + "'");
    returnMessage(request.message);
});

function returnMessage(messageToReturn) {
    chrome.tabs.query({active: true}, function(tabs) {
      var joinedMessage = messageToReturn + backgroundScriptMessage;
      alert("Background script is sending a message to contentscript:'" + joinedMessage +"'");
      chrome.tabs.sendMessage(tabs[0].id, {greeting: "hello"});
    });
}

当我解压在Chrome浏览器扩展插件,并点击生成图标时,看到2个警报

  1. 背景脚本已收到一则由contentscript:“从弹出来了”
  2. 背景脚本已收到一则由contentscript:紫色猴子洗碗机“从弹出来了”

并且从未示出的第三弹出其是存在于contentscript。 我试图寻找错误,但没有运气。 是否有人有一个解决方案?

Answer 1:

当查询当前激活的标签,不要忘了添加currentWindow: true

function returnMessage(messageToReturn) {
    chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
      var joinedMessage = messageToReturn + backgroundScriptMessage;
          alert("Background script is sending a message to contentscript:'" + joinedMessage +"'");
      chrome.tabs.sendMessage(tabs[0].id, {greeting: "hello"});
    });
}

然后,请使用runtime.onMessage代替extension.onMessage

顺便说一句,你还可以使用sender.tab.id获得在发件人ID标签runtime.onMessage监听器,那么你就不会需要查询的选项卡状态。



文章来源: Chrome extension message passing from background script to content script is not working