0

我正在编写一个 Firefox WebExtension,chrome.storage.local用于保存状态,这是我第一次选择扩展时所做的。

如何将状态限制为特定选项卡?我希望每个选项卡都有自己的数据版本。

谢谢

4

1 回答 1

0

与大多数存储方法一样,您必须在存储的数据上强加一种结构,以便您可以根据需要存储和检索数据。在这种情况下,您可以将数据set()get()特定选项卡相关联。有很多方法可以做到这一点。组织数据的“最佳”方式取决于您存储的数据、您在概念上组织数据的方式以及每个选项卡的独特之处(从您的扩展程序的角度来看;即为什么数据由制表符分隔,这可能是它实际上是由 URL 分隔,而不是制表符)。

您正在尝试做的事情有太多未指定的部分,无法为您提供关于组织数据的“最佳”方式的好建议。但是,以下是一种可能的方法示例:

// callback to get and set() just checks for errors
function reportIfStorageError() {
    if (chrome.runtime.lastError) {
        console.log(chrome.runtime.lastError);
    }
}
function getKeyForTab(tab) {
    //Use a key that is a combination of text that for this add-on is
    //  unique to data being stored for a tab, "tabData", plus the tab's ID.
    //  This allows set/get to be just for the data for the tab while
    //  laving all other keys that don't start with "tabData" available
    //  to store any other non-tab related data we desire. In other words,
    //  we don't need to worry about a conflict between some unknown tab ID
    //  and any other key we choose to use.
    return "tabData" + tab.id;
}
function getLocalStorageForTab(tab, theTabsCompleteDataObject) {
    let key = getKeyForTab(tab);
    chrome.storage.local.get({key: theTabsCompleteDataObject}, reportIfStorageError);
    return theTabsCompleteDataObject;
}
function setLocalStorageForTab(tab, theTabsCompleteDataObject) {
    let key = getKeyForTab(tab);
    chrome.storage.local.set({key: theTabsCompleteDataObject}, reportIfStorageError);
}

在上面的示例中,为选项卡创建了一个键,该键对于该选项卡是唯一的。为此,我们选择一个前缀 ,tabData对于这个附加组件,我们将其定义为始终启动用于选项卡数据的键。这样做是因为我们无法控制选项卡的 ID。如果我们只使用 ID 作为密钥,我们将不得不考虑 ID 与我们用来存储其他数据的密钥匹配的可能性。这样,我们只需为其他不以 . 开头的数据选择键tabData。特定选项卡的完整键是前缀,tabData与选项卡的 ID 连接tab.id

tab提供给两者和getLocalDataForTab()setLocalDataForTab()选项tabs.Tab卡。该变量是包含与选项卡关联的所有数据theTabsCompleteDataObject的单个对象。

于 2016-07-15T07:52:04.920 回答