Chrome.runtime.onMessage不起作用

时间:2014-04-24 13:18:50

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

我正在构建chrome.extension。

在其中,我button中有一个popup.html(显示在右上方的工具栏中)。 popup.html文件链接到HTMLjs.js文件,该文件包含以下代码:

(function(){
    window.onload = init;

    function init(){
        if (!chrome.runtime) {
            // Chrome 20-21
            chrome.runtime = chrome.extension;
        } else if(!chrome.runtime.onMessage) {
            // Chrome 22-25
            chrome.runtime.onMessage = chrome.extension.onMessage;
            chrome.runtime.sendMessage = chrome.extension.sendMessage;
            chrome.runtime.onConnect = chrome.extension.onConnect;
            chrome.runtime.connect = chrome.extension.connect;
        }

        button.onclick = function(){

            console.log("Working onclick!"); // working!

            // send the message to the content script
            chrome.runtime.sendMessage(["testing"]); 
        }
    }
})();

popup.js(在stackoverflow等网页上运行,可能称为content-script)具有以下代码:

 (function () {
     window.onload = init;

     function init() {
         if (!chrome.runtime) {
             // Chrome 20-21
             chrome.runtime = chrome.extension;
         } else if (!chrome.runtime.onMessage) {
             // Chrome 22-25
             chrome.runtime.onMessage = chrome.extension.onMessage;
             chrome.runtime.sendMessage = chrome.extension.sendMessage;
             chrome.runtime.onConnect = chrome.extension.onConnect;
             chrome.runtime.connect = chrome.extension.connect;
         }

         // when receiving the message from html popup.html
         chrome.runtime.onMessage.addListener(function (message, MessageSender, sendReponse) {
             // Sender MessageSender: https://developer.chrome.com/extensions/runtime#type-MessageSender
             // function sendResponse: needed to send response, not needed in current context (?)

             console.log(message); // not work
             console.log("W"); // not work
             alert("W"); // not work
             sendReponse(); // not work

             return true;
         });
     }
 })();

我打开了两个控制台(stackoverflow网页和popup.html),只有console.log("Working onclick!");有效。内容脚本似乎根本没有收到该消息。

如果重要的话,这是manifest.json

UPDATE:

使用接受的答案,我需要:

// get the active tab, and send its id along with message using tabs.sendMessage
chrome.tabs.query({active:true}, function(tabs){
    // send the message to the content script
    chrome.tabs.sendMessage(tabs[0].id, ["testing"]);               
});

1 个答案:

答案 0 :(得分:4)

要向内容脚本发送消息,您需要使用chrome.tabs.sendMessage