S
S
SavaLLL2015-08-06 14:43:52
JavaScript
SavaLLL, 2015-08-06 14:43:52

How to do messaging in Chrome Extension?

I need to implement messaging in an extension. From content_script in background.js, I looked in the documentation for a way to exchange using window.postMessage() and window.addEventListener(), but no messages are sent. Through content_script, js code is loaded in my head.
Here is the code in 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 one 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 one in inject.js:
window.postMessage({ type: "FROM_PAGE", text: "Hello from the webpage!" }, "*");

manifest.json:
{
  "name": "SaveImg",
  "description": "Shows some of the features of the Context Menus API",
  "version": "1.0",
    "content_scripts": [{
      "matches": ["http://*/*"],
      "js": ["contentscript.js"]
    }],
  "permissions": ["contextMenus", "storage","activeTab"],
  "background": {
    "scripts": ["sample.js"]
  },
  "web_accessible_resources": ["inject.js"],
  "manifest_version": 2
}

What am I doing wrong?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question