0

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?

SavaLLL
  • 39
  • 4
  • `window` object in the background page refers to itself, not the page currently viewed. As for what you are doing wrong - everything. Have you read [the documentation](https://developer.chrome.com/extensions/content_scripts) and examined [the official sample extensions](https://developer.chrome.com/extensions/samples)? – wOxxOm Aug 06 '15 at 13:09

2 Answers2

1

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

Community
  • 1
  • 1
cesarpachon
  • 1,179
  • 2
  • 10
  • 23
  • I can`t use chrome API in inject.js. What do? – SavaLLL Aug 06 '15 at 13:50
  • 1
    you can if you inject the script using: chrome.tabs.executeScript(null, {file: "my_file.js"}); I used that script to send a message to the background.js using chrome.api. – cesarpachon Aug 06 '15 at 14:49
0

The basic flow of communication between a webpage and a content script or background script is:

Use content scripts to share DOM with the Web, use window.postMessage to send messages, and content.js uses extended API to forward the message to background.js after receiving the message.

manifest.json

{
  "name": "you name",
  "description": "you description",
  "version": "1.1.0",
  "background": {
    "scripts": ["background.js"],
    "persistent": false
  },
  "content_scripts": [
    {
      "matches": ["<all_urls>"],
      "js": ["content.js"],
      "all_frames": true
    }
  ],
  "manifest_version": 2
}

web.html

<body>
  <button id="me">Button</button>
</body>

content.js

window.addEventListener('message', event => {
  chrome.runtime.sendMessage(`${event.data} forwarded to the background.js`);
});

document.querySelector('#me').addEventListener('click', () => {
  window.postMessage('Message from DOM', '*');
});

background.js

chrome.runtime.onMessage.addListener(msg => console.log(msg));

Long-lived connections

content.js

const port = chrome.runtime.connect();
window.addEventListener('message', event => {
  port.postMessage(event.data);
});

document.querySelector('#me').addEventListener('click', () => {
  window.postMessage('Message from DOM', '*');
});

background.js

chrome.runtime.onConnect.addListener(port => {
  port.onMessage.addListener(msg => {
    console.log('msg: ', msg);
  });
});

Another way to communicate directly with background.js

manifest.json (add externally_connectable)

{
  "name": "you name",
  "description": "you description",
  "version": "1.1.0",
  "background": {
    "scripts": ["background.js"],
    "persistent": false
  },
  "content_scripts": [
    {
      "matches": ["<all_urls>"],
      "js": ["content.js"],
      "all_frames": true
    }
  ],
  "manifest_version": 2,
  "externally_connectable": {
    "matches": ["http://localhost/*"]
  }
}

web.html

<body>
  <button id="me">Button</button>
  <script>
   // Your extension ID, (pabahpeigkdpglhnjponplchdffchkdj).
    document.querySelector('#me').addEventListener('click', () => {
      chrome.runtime.sendMessage('pabahpeigkdpglhnjponplchdffchkdj', 'Web Message');
    });
  </script>
</body>

background.js

chrome.runtime.onMessageExternal.addListener(request => {
  console.log('request: ', request);
});

weiya ou
  • 2,730
  • 1
  • 16
  • 24