如何与嵌入页面Chrome扩展程序通信?

时间:2015-08-06 13:04:20

标签: javascript google-chrome-extension

我需要在扩展中实现消息传递。来自background.js中的content_script`a寻找使用window.postMessage()和window.addEventListener()交换文档的方法,但不发送消息。通过content_script我在头部加载了js代码。 这是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);

这在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);
};

这在inject.js中:

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

我做错了什么?

2 个答案:

答案 0 :(得分:1)

你应该使用:

chrome.runtime.onMessage.addListener

chrome.runtime.sendMessage

在不同的js组件之间传递消息。这个答案对我很有帮助:Chrome Extension how to send data from content script to popup.html

答案 1 :(得分:0)

网页和内容脚本或后台脚本之间的基本通信流程是:

使用内容脚本与Web共享DOM,使用window.postMessage发送消息,content.js使用扩展API在收到消息后将消息转发给background.js。

ma​​nifest.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));

长期连接

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);
  });
});

另一种直接与 background.js 通信的方式

ma​​nifest.json(添加 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);
});