sending message to chrome extension from a web page

前端 未结 5 525
遇见更好的自我
遇见更好的自我 2020-11-27 13:24

I want to send message from the console of the random web page to my chrome extension. chrome.extension.sendMessage doesn\'t seem to work.

5条回答
  •  执念已碎
    2020-11-27 13:53

    According to the official docs you should use postMessage in the sender and message event listener in the receiver.

    Here is an example:

    Your website's page.html

    var data = { type: "FROM_PAGE", text: "Hello from the webpage!" };
    window.postMessage(data, "*");
    

    Content script: (injected using chrome.tabs.executeScript(tabid, {code:...)

    window.addEventListener("message", function(event) {
        // We only accept messages from ourselves
        if (event.source != window)
            return;
    
        if (event.data.type && (event.data.type == "FROM_PAGE")) {
            console.log("Content script received message: " + event.data.text);
        }
    });
    

    Here page.html (which is not a part of the extension) posts messages to itself, which are intercepted and inspected by the content script. The reverse is possible through similar means.

    To pass from content script to extension, you will have to use one of the available message-passing techniques.

    It looks complicated and it is somewhat complicated but all this mumbo-jumbo is very secure.

提交回复
热议问题