How to disable (gray out) page action for Chrome extension?

后端 未结 1 1092
-上瘾入骨i
-上瘾入骨i 2021-01-26 04:32

I want the Chrome extension icon to be disabled (grayed out) on all pages except for pages on docs.google.com. This is my code in background.js.

\'use strict\';

         


        
相关标签:
1条回答
  • 2021-01-26 04:58

    This is a bug in Chrome and so far it's unclear if it's even fixable.

    Meanwhile, you can maintain the icon yourself:

    1. make a grayscale version of the icon(s) in any image editor and save them separately

    2. specify the gray icon in in manifest.json:

      "page_action": {
        "default_icon": {
          "16": "icons/16-gray.png",
          "32": "icons/32-gray.png"
        }
      }
      
    3. set the normal icon using SetIcon action:

      chrome.declarativeContent.onPageChanged.removeRules(async () => {
        chrome.declarativeContent.onPageChanged.addRules([{
          conditions: [
            new chrome.declarativeContent.PageStateMatcher({
              pageUrl: { hostPrefix: 'docs.google.' },
            }),
          ],
          actions: [
            new chrome.declarativeContent.SetIcon({
              imageData: {
                16: await loadImageData('icons/16.png'),
                32: await loadImageData('icons/32.png'),
              },
            }),
            new chrome.declarativeContent.ShowPageAction(),
          ],
        }]);
      });
      
      function loadImageData(url) {
        return new Promise(resolve => {
          const canvas = document.body.appendChild(document.createElement('canvas'));
          const context = canvas.getContext('2d');
          const img = new Image();
          img.onload = () => {
            context.drawImage(img, 0, 0);
            const data = context.getImageData(0, 0, img.width, img.height);
            canvas.remove();
            resolve(data);
          };
          img.src = url;
        });
      }
      

    Note, in the future ManifestV3 extension service worker you would use fetch + OffscreenCanvas in loadImageData.

    0 讨论(0)
提交回复
热议问题