Detect when Chrome extension was installed, without inline installation

自闭症网瘾萝莉.ら 提交于 2019-12-12 10:22:02

问题


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


来源:https://stackoverflow.com/questions/52347230/detect-when-chrome-extension-was-installed-without-inline-installation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!