簡體   English   中英

使用Chrome存儲API從本地存儲中存儲和檢索數據

[英]Store and retrieve data from local storage using chrome storage API

我正在構建擴展程序,該擴展程序向用戶顯示以秒為單位的值,以顯示用戶在特定網站上花費的時間。 我一切正常,但是每次退出chrome或重新啟動計算機時,時間變量都會從0開始重新計數。我認為使用chrome storage API可以完成這項工作。 瀏覽完API文檔后,我設法存儲了本地存儲並檢索了一個數字。 我無法做的是當用戶退出chrome時如何將數據保存到本地存儲中。 有沒有辦法檢測到這樣的事件?

首先,您無需使用chrome.storage API即可完成此工作。 順便說一句,不幸的是,您要找的東西不存在。 您正在尋找Chrome API中未實現的某些事件(例如onBrowserClosed )。 已在此處提交了錯誤報告(盡管它實際上不是錯誤),如果您想保持最新狀態,可以對其進行注視。

雖然,您仍然可以使用setInterval()解決問題,該函數將執行您的功能以更新用戶每隔一定間隔(以毫秒為單位)在網站上停留的時間,並在關閉瀏覽器時停止。 像這樣:

var currentActiveTab, chromeHasFocus = false;

localStorage.timeSpentOnSites = localStorage.timeSpentOnSites || "{}";

// get the first tab at startup
chrome.tabs.query({active: true, highlighted: true}, function(tabs) {
    currentActiveTab = tabs[0];
    console.log('New active tab:', tabs[0]);
});

// this will keep currentActiveTab updated to always be the active tab (the one that the user is watching)
chrome.tabs.onUpdated.addListener(function(tabID, info, tab) {
    if (tab.active && tab.highlighted) currentActiveTab = tab;
    console.log('New active tab:', tab);
});

// this also
chrome.tabs.onActivated.addListener(function(info) {
    chrome.tabs.query({active: true, highlighted: true}, function(tabs) {
        currentActiveTab = tabs[0];
        console.log('New active tab:', tabs[0]);
    });
});

// this will check if chrome is active or not
chrome.windows.onFocusChanged.addListener(function(windowID) {
    if (windowID === chrome.windows.WINDOW_ID_NONE) {
        chromeHasFocus = false;
        console.log('Chrome lost focus.');
    } else if (!chromeHasFocus) {
        chromeHasFocus = true;
        console.log('Chrome has focus.');
    }
});

function addTimeSpentOnSite(site) {
    var T = JSON.parse(localStorage.timeSpentOnSites);

    // if site already exists increment the time spent on it
    if (T[site]) T[site]++;
    // otherwise set the time spent on it as 1 (second)
    else T[site] = 1;

    localStorage.timeSpentOnSites = JSON.stringify(T);
}

setInterval(function() {
    if (!chromeHasFocus) return;
    // if the chrome window isn't active the user is not watching the site

    var site = currentActiveTab.url.split('/')[2]; 
    // get the site name, something like www.site.com

    addTimeSpentOnSite(site);
    // increase the amount of time spent on the site
}, 1000);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM