在聊天中 Florian的推动下,我使用第二个chrome.storage
空格提出了以下解决方案。
我已经在检查用户的 Chrome 存储中是否存在样式表,如果不存在,则从扩展文件中加载样式表。为了让它在更改时自动更新,我现在chrome.storage
在检查是否从 Chrome 的存储中加载样式表时检查第二个包含版本号的空间。基本方法如下:
// Helper function that checks whether an object is empty or not
function isEmpty(obj) {
return Object.keys(obj).length === 0;
}
var stylesheetObj = {}, // Keeps track of all stylesheets
stylesheetVersion = 1; // THIS NUMBER MUST BE CHANGED FOR THE STYLESHEETS TO KNOW TO UPDATE
chrome.storage.sync.get('just-read-stylesheets', function (result) {
// Here 'results' is an object with all stylesheets if it exists
// This keeps track of whether or not the user has the latest stylsheet version
var needsUpdate = false;
// Here I get the user's current stylesheet version
chrome.storage.sync.get('stylesheet-version', function (versionResult) {
// If the user has a version of the stylesheets and it is less than the cufrent one, update it
if(isEmpty(versionResult)
|| versionResult['stylesheet-version'] < stylesheetVersion) {
chrome.storage.sync.set({'stylesheet-version': stylesheetVersion});
needsUpdate = true;
}
if(isEmpty(result) // Not found, so we add our default
|| isEmpty(result["just-read-stylesheets"])
|| needsUpdate) { // Update the default stylesheet if it's on a previous version
// Open the default CSS file and save it to our object
var xhr = new XMLHttpRequest();
xhr.open('GET', chrome.extension.getURL('default-styles.css'), true);
// Code to handle successful GET here
}
xhr.send();
return;
}
// Code to do if no load is necessary here
});
});
这样一来,为用户更新样式表唯一需要更改的是stylesheetVersion
,确保它比以前的版本大。例如,如果我更新了样式表并希望用户的版本自动更新,我会stylesheetVersion
从更改1
为1.1
.
如果需要更完整的实现,可以在 GitHub 上找到 JS 文件