Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make chrome extension work only on certain sites (manifest v3)

I ran into some trouble when upgrading to manifest v3, and would greatly appreciate your help and input.

Background:

  • Using manifest v3
  • Using ShowAction() instead of ShowPageAction() which is deprecated
  • Used to work with manifest v2 and ShowPageAction()
  • Already read this post which did not apply to manifest v3 (or seemed like it didn't apply)
  • Also followed this google guide for upgrading from ShowPageAction to ShowAction

After following chrome's tutorial, which is reposted below:

    // background.js

    // Wrap in an onInstalled callback in order to avoid unnecessary work
    // every time the background script is run
    chrome.runtime.onInstalled.addListener(() => {
      // Page actions are disabled by default and enabled on select tabs
      chrome.action.disable();
    
      // Clear all rules to ensure only our expected rules are set
      chrome.declarativeContent.onPageChanged.removeRules(undefined, () => {
        // Declare a rule to enable the action on example.com pages
        let exampleRule = {
          conditions: [
            new chrome.declarativeContent.PageStateMatcher({
              pageUrl: {hostSuffix: '.example.com'},
            })
          ],
          actions: [new chrome.declarativeContent.ShowAction()],
        };
    
        // Finally, apply our new array of rules
        let rules = [exampleRule];
        chrome.declarativeContent.onPageChanged.addRules(rules);
      });
    });

I noticed that the icon on my extension grey's out on sites that don't match the specified pattern, and has color on sites that do match the url pattern (expected behavior). However, when I click on the extension on sites that match the url pattern, the extension remains disabled.

Question: Has anyone been able to get this sample code to work? How would one make a chrome extension work only when user is on specific site, and has clicked on the extension?

Thanks in advance!

like image 669
river Avatar asked Sep 20 '25 10:09

river


1 Answers

You just need to add "declarativeContent" into manifest.json permissions.

 "permissions": [
     "declarativeContent"
],
like image 65
Anton Avatar answered Sep 23 '25 11:09

Anton