如果扩展程序的文件发生更改,请更新 chrome.storage

Update chrome.storage if extension's file changes

本文关键字:更新 storage chrome 程序 扩展 文件 如果      更新时间:2023-09-26

我有一个Chrome扩展程序,它使用chrome.storage来跟踪样式表以应用于页面的内容。这些样式表之一是必需的默认样式表,如果该文件在用户的chrome.storage中不存在,我最初会从 Chrome 的扩展文件中加载该文件。这很好用。

但是,我有时会使用不同的规则更新此默认样式表以改进样式。当扩展运行时,它会检查默认样式表是否存在并找到旧版本的样式表 - 因此它不会从扩展的存储中加载任何内容。因此,用户仍在使用旧版本的样式表。

在我的本地计算机上,我可以手动清空我的chrome.storage并加载新的,但我无法在扩展程序发布时通过扩展程序执行此操作,因为我不想每次扩展运行时都清空它,也不知道只有样式表在 Chrome 的扩展文件中更新的时间。

我可以通过检查两个文件的每个字符,比较它们是否相同,如果是这样,加载扩展的样式表来解决这个问题,但这似乎是矫枉过正并且容易出错。

有没有更简单的方法只有在更新扩展的样式表而不更改文件名的情况下更新chrome.storage的样式表?

如果你想看看我的实现,整个项目都是在GitHub上开源的。

在聊天中弗洛里安的推动下,我使用第二个chrome.storage空间提出了以下解决方案。

我已经在检查用户的 Chrome 存储中是否存在样式表,如果不存在,则从扩展程序的文件加载样式表。为了使它在更改时自动更新,我现在在检查是否从 Chrome 的存储加载样式表时检查第二个chrome.storage空间,其中包含版本号。基本方法如下:

// 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 ,确保它比以前的版本大。例如,如果我更新样式表并希望用户的版本自动更新,我会将stylesheetVersion1 更改为 1.1

如果你需要一个更完整的实现,你可以在GitHub上找到JS文件

尝试使用 chrome.storage.sync 并将侦听器添加到其*onChanged*事件中。每当存储发生任何更改时,都会触发该事件。下面是侦听保存更改的示例代码:

chrome.storage.onChanged.addListener(function(changes, namespace) {
    for (key in changes) {
        var storageChange = changes[key];
        console.log('Storage key "%s" in namespace "%s" changed. ' +
        'Old value was "%s", new value is "%s".',
        key,
        namespace,
        storageChange.oldValue,
        storageChange.newValue);
    }
});