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