I just started working on a chrome extension which wasnt build by me and its also my very first chrome extension i work on.
The extension gathers data from the current webpage im on (content-script.js) and when clicking the chrome extension button, the plugin.js displays those data.
But unfortunately those data are shared around other tabs the chrome extension is also open.
For example: Im on tab A and click the Chrome Extension button so the popup opens and all is fine. Afterwards i navigate to tab B and also open the chrome extension. Then i see the data of tab B as expected. But after navigating back to tab A, i also see the data of tab B in the Plugin.
How can i avoid this? If i navigate between browser windows (not tabs) everything is fine. If i use some logging i also see that all tabs get this logging even if the logging should only be in tab A (the tab in which i performed some action to trigger the logging) for example.
Here is a code snipped:
Content-script.js:
//gather some website data like metatags etc and collect them
//afterwards connect and post a message to background.js
const port = browser.runtime.connect({ name: "content_script_port" });
window.setTimeout(() => {
port.postMessage({
message: "some-message",
metatags: metatags
.....
Background.js
browser.runtime.onConnect.addListener(port => {
const tab = port.sender.tab;
port.onMessage.addListener(message => {
// Send the tab ID with the message
message.tabId = tab.id;
// Send the message to the popup
browser.runtime.sendMessage(message);
});
});
Plugin.js
//receive the message send from content-script to background to plugin
browser.runtime.onMessage.addListener((request) => {
//get active browser tab
browser.tabs.query({ active: true, currentWindow: true }, function(tabs) {
const tabId = tabs[0].id;
if( request.tabId === tabId){
//do here something with the data and show it in the popup
I already tried alot here besides the shown solution with browser.runtime.connect for example with chrome.tabs or chrome.runtime.sendMessage.