Hello, people of Mozilla Discourse!
I am trying to make an add-on and I am currently stuck on passing data from the background script to the popup(?) script.
My directory structure is very simple right now.
├── background.js
├── manifest.json
├── popup.js
└── tabs.html
My manifest.json
looks like this.
{
"manifest_version": 2,
"name": "Borderify",
"version": "1.0",
"description": "Adds a red border to all webpages matching mozilla.org.",
"icons": {
"48": "icons/border-48.png"
},
"permissions": [
"<all_urls>",
"tabs"
],
"background": {
"scripts": ["background.js"]
},
"browser_action": {},
"browser_specific_settings": {
"gecko": {
"id": "borderify@example.com"
}
}
}
Inside tabs.html
, it has a script tag that references popup.js
.
What I would like is to pass some data (an array, to be more specific) from background.js
when the user clicks on the add-on icon. This has been set up like such:
browser.runtime.onConnect.addListener((port) => {
console.log('background.js connected to general port!', port);
port.postMessage({ msg: 'Hi from background.js again!' });
port.onMessage.addListener((msg) => {
console.log('Received in background.js through general port:', msg);
});
});
browser.browserAction.onClicked.addListener(async () => {
// ...
browser.tabs.create({ url })
.then((tab) => {
const port = browser.tabs.connect(tab.id);
console.log('background.js connected to tab port.');
// the data would be an array but this is a decent example!
port.postMessage('Hello from background.js, through tab port!');
}, onError);
});
And inside popup.js
:
console.log('popup.js is running!');
browser.runtime.onConnect.addListener((port) => {
console.log('popup.js connected to general port', port);
port.onMessage.addListener((msg) => {
console.log('Listened to a message in popup.js:', msg);
});
port.postMessage({ msg: 'Hi from popup.js again, but from the general port' });
});
browser.tabs.query({ active: true, currentWindow: true })
.then(tabs => {
const { id } = tabs[0];
const port = browser.tabs.connect(id);
port.postMessage({ msg: 'Hi from popup.js again' });
});
This is the output:
“background.js connected to tab port.”
“popup.js is running!”
“popup.js connected to general port
Object { name: “”, sender: {…}, error: null, onMessage: {…}, onDisconnect: {…}, postMessage: (), disconnect: () }”
“Listened to a message in popup.js:
Object { msg: “Hi from popup.js again” }”
If background.js
and popup.js
are connected to the same tab port, why is it that the former is not receiving anything? In fact, it looks like popup.js
is just talking and listening to itself. The messages that were supposed to be sent were never sent to each other.
I would appreciate any help.