Sending messages from background script or popup not working in Chrome or Firefox
Messaging sending is not working for me
Link to related repo Firefox version: 95.0.2 Chrome version: 96.0.4664.110
Explanation
I tried to follow the docs, but the onMessage and sendMessage do no appear to be working for me in either browser.
The main error I saw when installing was this, but I am unclear from the docs how to pass a tab id.
You can see how I pass the tab ID in the background script code below.

Code
You can also clone and check out the related repo Manifest:
{
"name": "webext test",
"version": "1.0",
"manifest_version": 2,
"content_scripts": [
{
"matches": ["<all_urls>"],
"js": ["content_script.js"]
}
],
"background": {
"scripts": ["background.js"],
"persistent": false
},
"browser_action": {
"default_popup": "popup.html"
},
"permissions": [
"storage",
"activeTab"
]
}
Popup
import { sendMessage } from 'webext-bridge'
const button = document.getElementsByTagName('button')[0]
button.addEventListener('click', async() => {
const res = await sendMessage('from-popup', {message: 'Hello World'}, 'content-script');
console.log('popup result: ', { res })
})
Content Script
import { sendMessage, onMessage } from 'webext-bridge'
console.log('content script loaded');
onMessage('from-popup', async(message) => {
console.log(message)
})
onMessage('from-background', async(message) => {
console.log(message)
})
Background script
import 'webext-bridge';
import { sendMessage } from 'webext-bridge'
console.log('hello from background script');
const currentTab = browser.tabs.query({active: true, currentWindow: true}).then(tabs => tabs[0])
sendMessage('from-background', {message: 'Hello World from background script'}, {context: 'content-script', tabId: currentTab.id });
Expected result
All console log messages in the content script should appear when the extension is loaded into Firefox or Chrome.
When I click the popup button, I should see a console.log of {message: "Hello World"}
Actual result
The only console message I see is 'content script loaded'
Urgency
Not urgent. I ended up using webextension-polyfill with browser.runtime.sendMessage and browser.tabs.sendMessage
I'm also having the same issue. Any ETA on this?
Old issue + the reproduction repo is a 404 but according to the readme, you specify the tab id with content-script@tabId :
Example :
devtoolsorcontent-scriptorbackgroundorcontent-script@133ordevtools@453.
The author might have another problem inside the backgrouns script. The currentTab variable looks like a Promise and not an id. (need to be awaited)
~Looks like sending message from popup to all pages (content-script) is not supported by this library. As sendMessage always expects id to be specified as content-script@id~
Chrome also limits sending messaing to all tabs at once. So I believe nothing wrong with this library.