Detect when Chrome extension was installed, withou

2019-06-08 15:07发布

问题:

How can an open tab get notified that a Chrome extension has just been installed, when the installation was done through the Chrome Web Store instead of inline-installation?

Context

Since June 2018 and onwards Chrome has deprecated inline installation hence the following mechanism to get notified if extension was installed won't work from now on:

chrome.webstore.install(url, successCallback, failureCallback)

From now on extensions must be installed only via the Web Store.

We've built a screen share extension that allows prompting the user to share his screen.

When our users hit "Share Screen", we intend to redirect them to the Chrome extension within the Web Store and as soon as they install the extension to re-trigger the Share Screen functionality.

回答1:

Here's how I solved it from the background script (w/o using a content script):

background.js

  • Listen for onInstalled event.
  • Query all opened tabs that match the URL's you want to notify.
  • Execute a small script in each tab that will postMessage notifying that installation was succesful.
chrome.runtime.onInstalled.addListener(function listener(details) {
  if (details.reason === chrome.runtime.OnInstalledReason.INSTALL) {
    chrome.tabs.query({
      url: [
        'https://localhost:3000/*',
        'https://staging.foo.com/*',
        'https://production.foo.com/*'
      ]
    }, tabs => {
      Array.from(tabs).forEach(tab => {
        chrome.tabs.executeScript(tab.id, {
          code: `window.postMessage('screenshare-ext-installed', window.origin);`
        });
      });
    });

    chrome.runtime.onInstalled.removeListener(listener);
  }
});

manifest.json

Just make sure both externally_connectable and permissions declare the URL patterns of the sites you want to notify.

"externally_connectable": {
    "matches": [
    "https://localhost:3000/*",
    "https://staging.foo.com/*",
    "https://production.foo.com/*"
  ]
},
"permissions": [
  "desktopCapture",
  "https://localhost:3000/*",
  "https://staging.foo.com/*",
  "https://production.foo.com/*"
],

Web page

Just listen somewhere for the postMessage message fired by the extension on succesful installation.

window.onmessage = e => {
  if (e.data === 'screenshare-ext-installed') {
    // extension successfully installed
    startScreenShare()
  }
}

Credits

  • @wOxxOm's comment