Check whether user has a Chrome extension installed

前端 未结 16 2320
一向
一向 2020-11-22 08:50

I am in the process of building a Chrome extension, and for the whole thing to work the way I would like it to, I need an external JavaScript script to be able to detect if

16条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-22 09:08

    Another method is to expose a web-accessible resource, though this will allow any website to test if your extension is installed.

    Suppose your extension's ID is aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa, and you add a file (say, a transparent pixel image) as test.png in your extension's files.

    Then, you expose this file to the web pages with web_accessible_resources manifest key:

      "web_accessible_resources": [
        "test.png"
      ],
    

    In your web page, you can try to load this file by its full URL (in an tag, via XHR, or in any other way):

    chrome-extension://aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/test.png
    

    If the file loads, then the extension is installed. If there's an error while loading this file, then the extension is not installed.

    // Code from https://groups.google.com/a/chromium.org/d/msg/chromium-extensions/8ArcsWMBaM4/2GKwVOZm1qMJ
    function detectExtension(extensionId, callback) { 
      var img; 
      img = new Image(); 
      img.src = "chrome-extension://" + extensionId + "/test.png"; 
      img.onload = function() { 
        callback(true); 
      }; 
      img.onerror = function() { 
        callback(false); 
      };
    }
    

    Of note: if there is an error while loading this file, said network stack error will appear in the console with no possibility to silence it. When Chromecast used this method, it caused quite a bit of controversy because of this; with the eventual very ugly solution of simply blacklisting very specific errors from Dev Tools altogether by the Chrome team.


    Important note: this method will not work in Firefox WebExtensions. Web-accessible resources inherently expose the extension to fingerprinting, since the URL is predictable by knowing the ID. Firefox decided to close that hole by assigning an instance-specific random URL to web accessible resources:

    The files will then be available using a URL like:

    moz-extension:///
    

    This UUID is randomly generated for every browser instance and is not your extension's ID. This prevents websites from fingerprinting the extensions a user has installed.

    However, while the extension can use runtime.getURL() to obtain this address, you can't hard-code it in your website.

提交回复
热议问题