从弹出脚本向内容脚本chrome扩展发送消息

时间:2018-11-29 21:17:02

标签: javascript google-chrome popup message

我已经看到许多与此问题类似的问题,但是我已经进行了他们建议的更改,但仍然无法使它起作用。我在chrome扩展程序中运行了一个弹出脚本。我的弹出html中有一个按钮,当单击该按钮时,它会关闭弹出脚本。该脚本向我的内容脚本发送一条消息,以处理该消息。参见下面的代码:

清单:

{
"content_security_policy": "script-src 'self' 'unsafe-eval'; object-src 'self'",
"manifest_version": 2,
"version": "1.1", 
"name": "Map automation", 
"description": "do something",
"browser_action": {
    "default_icon": "worldmap.png",
    "default_popup": "popup.html"
},
"permissions": [ "tabs" ],
"content_scripts" : [
    {
        "matches": ["<all_urls>"],
        "js": ["content.js"]
    }
]
}

popup.js:

function popup() {
    console.log("popup started")
    chrome.tabs.query({currentWindow: true, active: true}, function (tabs){
        var currentTab = tabs[0]
        chrome.tabs.sendMessage(currentTab.id, {"message": "start"});
        console.log("message sent to " + currentTab.url)
    })
}

document.addEventListener("DOMContentLoaded", function() {
  document.getElementById("mybutton").addEventListener("click", popup);
});

content.js:

chrome.runtime.onMessage.addListener(MessageReceived);

function MessageReceived (request, sender, sendResponse) {
    console.log("message received")
    if (request.message == "start") {
        console.log("alert about to send")
        alert("received message :)")
    }
};    

我收到控制台日志确认,确认我的消息已发送到正确的URL,但是没有收到消息,也没有警报出现。我没有收到任何错误消息。我在这里想念什么?

0 个答案:

没有答案