How to Make popup.html on specific URL

Viewed 171

PopUp.html doesn't work on specific URL I want to enable popup.html to open on a specific URL just Like google.com for example

Manifest.json v3

{
  "name": "test",
  "version": "1.0",
  "description": "My Extension",
  "manifest_version": 3,
  "content_scripts": [
    {
      "matches": ["https://www.google.com/*"],
      "js": ["popup.js"],
      "css": ["style.css"]
    }
  ],"action": { 
      "default_popup" : "Popup.html"
    }
}

I tried with MV2 but it can't work inside the if condition()

Manifest.json v2

{
  "name": "testmv2",
  "version": "1.0",
  "description": "My Extension 2",
  "manifest_version": 2,
  "permissions": ["activeTab","tabs", "declarativeContent"],
      "background":{        
      "scripts": ["background.js"],
      "persistent": false
    },
  "content_scripts": [
    {
      "matches": ["https://www.google.com/*"],
      "js": ["popup.js"],
      "css": ["style.css"]
    }
  ],    "browser_action": { }
}

Backgound.js

document.addEventListener('DOMContentLoaded', function() {

'use strict';

chrome.tabs.getSelected(null, function(tab) {
    myFunction(tab.url);
});

function myFunction(tablink) {
var mySiteUrl = 'https://www.google.com/';

    if( tablink === mySiteUrl){
        //it's the right website
        chrome.browserAction.setPopup({popup: "Popup.html"});

    }
}
})
1 Answers

This answer is supported in mv3.

As @bradcush said, you cannot use normal addEventListener in background.js. To keep it simple, background.js is more like server.js with no direct access to DOM element.

In your context, you will need to

  1. addListener on chrome.tabs.onUpdated for change in tab
  2. if the current tab's url is what you want, setPopup
  3. else setPopup to empty.
// background.js

chrome.tabs.onUpdated.addListener((tabId, changeInfo, tab) => {

    // Additionally, you can check for changeInfo.status

    if (/^https:\/\/www.google.com/.test(tab.url)) {  
        chrome.action.setPopup({ popup: "./popup.html"})
    } else {
        chrome.action.setPopup({ popup: "" })
    }
});

For mv2

You will need to make corresponding change according to docs.

Related