Search code examples
javascriptgoogle-chromegoogle-chrome-extensiongoogle-developer-tools

Popup.html is the same in all tabs (Chrome extension)


My extension checks for broken images on a website. Everything works fine if I open an URL at a time but if I open several URLs from one site, the summary in popup.html is always the same as the active tab (it's not updated for each site).

I don't know how to refer to the actual URL of the analysis and avoid the "active tab". Any ideas?

Manifest.json

{
"name": "Test",
"permissions": ["activeTab", "declarativeContent", "storage","tabs"],
"version": "1.0.0",
"description": "Test",

"background": {
    "scripts": ["background.js"],
    "persistent": false
  },

"content_scripts": [
  {
    "matches": ["http://*/*", "https://*/*", "https://www.google.com/_/chrome/newtab*"],
    "exclude_globs": ["*#*"],
    "js": ["jquery-3.4.1.min.js", "content.js"]
  }
],

"web_accessible_resources": ["popup.html"],

 "browser_action": {
  "default_icon": {
    "16": "images/ico.png",
    "32": "images/ico.png",
    "48": "images/ico.png",
    "128": "images/ico.png"
  }
},
"manifest_version": 2

}

Content.js

  chrome.runtime.onMessage.addListener((msg, sender, response) => {
  if (msg.subject === 'DOMInfo') {      
    var domInfo = {
      images: number_images   
    };
    response(domInfo);
  }
});

Popup.js

window.addEventListener('DOMContentLoaded', () => {
  chrome.tabs.query({
    active: true,
    currentWindow: true
  }, tabs => {
    chrome.tabs.sendMessage(
        tabs[0].id,
        {subject: 'DOMInfo'},
        setDOMInfo);
  });
});

I'm pretty sure is the tabs[0].id that causes the problem but I'm not sure how I can refer to the current URL that run the content.js script and make sure the popup.html gets the analysis from this URL. Any ideas?

In the background.js I had no problem referring the sender tab:

chrome.runtime.onMessage.addListener(function(msg, sender, sendResponse) 
{   
    chrome.tabs.query({active:true, windowType:"normal", currentWindow: true},function(d){

        var tabId =  sender.tab.id;     
        ....

Solution

  • Assuming popup.html is loaded into an iframe inside the web pages by your content script, you need chrome.tabs.getCurrent that returns the tab where this code is running so each iframe will find its own tab:

    chrome.tabs.getCurrent(tab => {
      chrome.tabs.sendMessage(tab.id, {subject: 'DOMInfo'}, callback);
    });
    

    P.S. When using sender.tab.id you don't need chrome.tabs.query - you already have the id.