Contents scripts run in the context of a web page, sometimes they need to communicate with other tabs. However, they cannot directly communicate with each other.
One common method is to use the background script as a mediator:
- Content scripts in different tabs send messages to the background script using
chrome.runtime.sendMessage()
. - The background script receives these messages and can then forward them to the appropriate tab using
chrome.tabs.sendMessage()
.
Sending a request from a content script looks like this:
content-script-a.js
1 | (async () => { |
Next we need to add a listener for messages comming from content scripts in the background script, then forward them to the target tabs.
1 | chrome.runtime.onMessage.addListener(async (message, sender, sendResponse) => { |
To receive the message in the desired tab, set up a runtime.onMessage
event listener in the content script:
1 | chrome.runtime.onMessage.addListener(function(message, sender, sendResponse) { |