Javascript 使用chrome存储API从本地存储中存储和检索数据

Javascript 使用chrome存储API从本地存储中存储和检索数据,javascript,google-chrome,google-chrome-extension,Javascript,Google Chrome,Google Chrome Extension,我正在构建一个扩展,该扩展以秒为单位向用户显示用户在特定网站上花费的时间。我已使一切正常工作,但每次退出chrome或重新启动计算机时,时间变量都会从0开始重新计数。我认为使用chrome存储API应该可以完成这项工作。在阅读了API文档之后,我设法从本地存储器中存储和检索了一个数字。我不能做的是当用户退出chrome时如何将数据保存到本地存储。有没有办法检测这样的事件?首先,您不需要使用chrome.storageAPI来实现这一点。顺便说一句,不幸的是,你要找的东西并不存在。您正在查找Chr

我正在构建一个扩展,该扩展以秒为单位向用户显示用户在特定网站上花费的时间。我已使一切正常工作,但每次退出chrome或重新启动计算机时,时间变量都会从0开始重新计数。我认为使用chrome存储API应该可以完成这项工作。在阅读了API文档之后,我设法从本地存储器中存储和检索了一个数字。我不能做的是当用户退出chrome时如何将数据保存到本地存储。有没有办法检测这样的事件?

首先,您不需要使用
chrome.storage
API来实现这一点。顺便说一句,不幸的是,你要找的东西并不存在。您正在查找ChromeAPI中未实现的某些事件(如
onBrowserClosed
)。已经制作了一个bug报告(虽然它实际上不是bug),如果你想保持更新,你可以启动它

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

是的,这正是我最终要做的。但是它不是效率低下吗?@nashmaniac是的,我知道,它有点效率低下,在setInterval中设置较小的毫秒数会使它工作得更慢,但这是目前唯一的解决方案。