Check whether user has a Chrome extension installed

前端 未结 16 2074
一向
一向 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:09

    A lot of the answers here so far are Chrome only or incur an HTTP overhead penalty. The solution that we are using is a little different:

    1. Add a new object to the manifest content_scripts list like so:

    {
      "matches": ["https://www.yoursite.com/*"],
      "js": [
        "install_notifier.js"
      ],
      "run_at": "document_idle"
    }
    

    This will allow the code in install_notifier.js to run on that site (if you didn't already have permissions there).

    2. Send a message to every site in the manifest key above.

    Add something like this to install_notifier.js (note that this is using a closure to keep the variables from being global, but that's not strictly necessary):

    // Dispatch a message to every URL that's in the manifest to say that the extension is
    // installed.  This allows webpages to take action based on the presence of the
    // extension and its version. This is only allowed for a small whitelist of
    // domains defined in the manifest.
    (function () {
      let currentVersion = chrome.runtime.getManifest().version;
      window.postMessage({
        sender: "my-extension",
        message_name: "version",
        message: currentVersion
      }, "*");
    })();
    

    Your message could say anything, but it's useful to send the version so you know what you're dealing with. Then...

    3. On your website, listen for that message.

    Add this to your website somewhere:

    window.addEventListener("message", function (event) {
      if (event.source == window &&
        event.data.sender &&
        event.data.sender === "my-extension" &&
        event.data.message_name &&
        event.data.message_name === "version") {
        console.log("Got the message");
      }
    });
    

    This works in Firefox and Chrome, and doesn't incur HTTP overhead or manipulate the page.

提交回复
热议问题