使用chrome storage API存储和检索本地存储中的数据

时间:2015-01-05 17:53:11

标签: javascript google-chrome google-chrome-extension

我正在构建扩展程序,扩展程序会在几秒钟内向用户显示用户在特定网站上花费的时间。我已经完成了所有工作,但每次退出chrome或计算机重新启动时,时间变量从0开始重新计数。我认为使用chrome storage API应该可以完成这项工作。在浏览API文档后,我设法从本地存储中存储和检索数字。我无法做的是当用户退出chrome时如何将数据保存到本地存储。有没有办法检测到这样的事件?

1 个答案:

答案 0 :(得分:1)

首先,您不需要使用chrome.storage API来完成这项工作。顺便说一下,不幸的是,你所寻找的东西并不存在。您正在寻找一些未在Chrome API中实施的活动(例如onBrowserClosed)。错误报告已经 HERE (虽然它实际上不是一个错误),如果你想保持更新,你可以为它加注星标。

尽管如此,您仍然可以使用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);
相关问题