Chrome extension: sendMessage doesn't work

后端 未结 3 1560
说谎
说谎 2021-01-06 09:28

I\'ve already read the documentation from Google on \'message passing\' a few times and have probably looked at over 10 other questions with the same problem and already tri

3条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-06 10:14

    Here is the solution, using background script:

    manifest.json

    {
        "manifest_version" : 2,
        "name" : "Message Test",
        "version" : "1.0",
    
        "background":{
            "scripts":["popup.js"]
        },
    
        "content_scripts": [
            {
            "matches" : [""],
            "js": ["message-test.js"]
            }
        ]
    }
    

    message-test.js

    var port = chrome.runtime.connect();
    port.onMessage.addListener(function(message, sender, sendResponse) {
        if (message.greeting == "Can you hear me?"){
            alert("Test");
        }
        else{
            sendResponse({});
        }
    });
    

    popup.js

    chrome.runtime.onConnect.addListener( function ( port ) {
    port.postMessage({
            greeting: "Can you hear me?"
        });
    });
    

    Some explanaition: first we are connecting to our background script from content script and then background script sends message to content script.

    Update

    I've improved answer according to @Xan remark. But the idea is the same, first of all you should let know your background script of the existence of content script.

提交回复
热议问题