Chrome extension attach properties to each tab

前端 未结 2 826
囚心锁ツ
囚心锁ツ 2021-01-16 17:58

In a chrome extension, I\'ve created tab properties that I\'m trying to store with each tab. What is the best way to do this? I\'ve looked into using localStorage, but it se

相关标签:
2条回答
  • 2021-01-16 18:21

    There's definitely no need to use localStorage. Without the notion "data is by no means permanent", one already knows that: tab IDs are unique within a session. From this fact, it follows that the data is non-persistent.

    The best method to implement it is to maintain a hash of tab properties:

    • chrome.tabs.onCreated (optional, add initial info to tab hash)
    • chrome.tabs.onUpdated - (Add/) Update tab hash (URL is available)
    • chrome.tabs.onRemoved - Remove hash entry

    Tab objects are not expensive: All properties are primitives (booleans, numbers, strings).

    For instance (background page only):

    var tabStore = {};         // <-- Collection of tabs
    chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) {
        tabStore[tabId] = tab;
    });
    chrome.tabs.onRemoved.addListener(function(tabId) {
        delete tabStore[tabId];
    });
    
    0 讨论(0)
  • 2021-01-16 18:31

    IMPORTANT ADDENDUM to Rob W's answer.

    Make sure to also listen to tabs.onReplaced as well, and update the tabStore accordingly.

    chrome.tabs.onReplaced.addListener(function(addedTabId, removedTabId) {
        tabStore[addedTabId] = tabStore[removedTabId];
        delete tabStore[removedTabId];
    });
    

    Chrome can change the id of a tab under the hood without warning or signs. As far as I know, the only place that this happens is the Google "instant search" when you type in a search into the address bar. It may be an edge case, but if you don't track this, it could end up being a very insidious problem.

    0 讨论(0)
提交回复
热议问题