Search code examples
javascriptgoogle-chrome-extension

How to Communication with the embedding page Chrome Extension?


I need to implement messaging in the expansion. From content_script`a in background.js looked for a way to exchange documents using window.postMessage () and window.addEventListener (), but the messages are not sent. Through content_script I loaded js code in head. Here's the code to background.js:

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:" + event.data.text);
    port.postMessage (event.data.text);
  }
}, False);

This in content_script.js:

var s = document.createElement ('script');
s.src = chrome.extension.getURL ('inject.js');
(Document.head || document.documentElement) .appendChild (s);
s.onload = function () {
    s.parentNode.removeChild (s);
};

This in inject.js:

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

What am i doing wrong?


Solution

  • you should use:

    chrome.runtime.onMessage.addListener
    

    and

    chrome.runtime.sendMessage
    

    to pass messages between different js components. this answer helped me a lot: Chrome Extension how to send data from content script to popup.html