如何在Chrome扩展自动更新时显示通知?
我的要求是在Chrome扩展自动更新后显示一个弹出窗口。
你可以监听 chrome.runtime.onInstalled
事件 ,当扩展程序被安装或更新时会触发该事件(如新的打包应用文档所述)。2019年更新:自答案提供于2012年以来,此事件已从dev转移到稳定通道。
chrome.runtime.onInstalled
的链接就是你所需要的。我不建议在更新时打开弹出窗口,因为那真的很烦人,但它可能会像这样:`chrome.runtime.onInstalled.addListener(function(details) {
if (details.reason == "update") {
chrome.windows.create({url: "popup.html", type: "popup"});
}
});`
- gengkev这里是完整的答案,对我很有效。
//=============== background.js =================
chrome.runtime.onInstalled.addListener(function (details) {
try {
var thisVersion = chrome.runtime.getManifest().version;
if (details.reason == "install") {
console.info("First version installed");
//Send message to popup.html and notify/alert user("Welcome")
} else if (details.reason == "update") {
console.info("Updated version: " + thisVersion);
//Send message to popup.html and notify/alert user
chrome.tabs.query({currentWindow: true, active: true}, function (tabs) {
for( var i = 0; i < tabs.length; i++ ) {
chrome.tabs.sendMessage(tabs[i].id, {name: "showPopupOnUpdated", version: thisVersion});
}
});
}
} catch(e) {
console.info("OnInstall Error - " + e);
}
});
//=============== popup.js =================
//Note: this has to be injected as content script from manifest.json
chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
switch (request.name) {
case "showPopupOnUpdated":
alert("Extension got updated to latest version: " + request.version);
break;
}
});
//=============== manifest.js =================
//Note: background.html needs to import background.js
{
"background": {
"page": "background.html"
},
"content_scripts": [
{
"js": [
"js/popup.js"
]
}
]
}