Safari扩展程序首次运行和更新 [英] Safari extension first run and updates
问题描述
在用户安装扩展程序后,如何知道我的Safari扩展程序代码是否第一次运行?
How can I know if my Safari extension code is running for the first time after the user has installed the extension?
我想区分扩展的新安装和扩展的更新.
I would like to differentiate between a new installation of the extension vs. an update of the extension.
我正在寻找与此答案非常相似的内容,但对于Safari,而不是适用于Chrome.在该链接中,我无法将答案中的代码翻译"到Safari.
I am looking for something very similar to this answer, but for Safari, instead of for Chrome. I haven't been able to "translate" the code from the answer in that link to Safari.
推荐答案
如果您可以不进行更新检查,则此脚本应该可以正常工作(与Chrome相关的答案比较):
If you can live without the update check, this script should work (compare with the Chrome related answer):
// In background page
function onInstall() {
console.log('Extension installed');
}
var firstRun = typeof localStorage['extensionHasPreviouslyRun'] === 'undefined' ||
!JSON.parse(localStorage['extensionHasPreviouslyRun']);
if (firstrun) {
onInstall();
localStorage['extensionHasPreviouslyRun'] = JSON.stringify(true);
}
如果还要检查更新,则需要从plist文件异步获取版本,如下所示:
If you want to check for updates also, you need to asynchronously get the version from the plist file, as so:
// In background page
function onInstall() {
console.log('Extension installed');
}
function onUpdate() {
console.log('Extension update');
}
function requestVersion(callback) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.open('GET', 'info.plist');
xmlhttp.onload = function () {
var infoFile = xmlhttp.responseXML;
var keys = infoFile.getElementsByTagName('key');
for (var i = 0; i < keys.length; i++){
if (keys[i].firstChild.data === 'CFBundleShortVersionString'){
var version = keys[i].nextElementSibling.firstChild.data;
callback(version);
break;
}
}
}
xmlhttp.send();
}
requestVersion(function(version) {
var storedVersion = localStorage['version'];
if (storedVersion !== version) {
// Check if we just installed this extension.
if (typeof storedVersion === 'undefined') {
onInstall();
} else {
onUpdate();
}
localStorage['version'] = version;
}
});
这篇关于Safari扩展程序首次运行和更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!