background script
content script
):
background.js
-
倾听
onInstalled
事件。
-
查询与要通知的URL匹配的所有打开的选项卡。
-
postMessage
通知
那次安装是成功的。
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
externally_connectable
permissions
声明
要通知的站点的URL模式。
"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/*"
],
网页
就在某个地方听音乐
消息激发者
window.onmessage = e => {
if (e.data === 'screenshare-ext-installed') {
// extension successfully installed
startScreenShare()
}
}
信用