Home > Software engineering >  How to get the time spent on a tab in Chrome?
How to get the time spent on a tab in Chrome?

Time:04-22

I am working on a chrome extension, and I need the time spent on each tab. I'm using chrome.tabs api.

CodePudding user response:

You need a timer, storage and tabs permissions and background Script.

The bg script needs an event and then check if its the desired URL:

window.addEventListener('load', function () {
    chrome.tabs.getSelected(null,function(tab){
        myURL=tab.url;
    });

If the desired URL is met, retrieve current timestamp and save it to a variable.

If the user closes the tab or chrome window catch it:

chrome.tabs.onRemoved.addListener(function(tabid, removed) {
 alert("tab closed")
})

chrome.windows.onRemoved.addListener(function(windowid) {
 alert("window closed")
})

Wihtin the catch you get the current timestamp again, calculate end - start and you could save it to e.g. sessionStorage.

CodePudding user response:

Maybe like a "chronometer", init a new Date() when your user open a tab and subtract a new Date() with the init time when your user close a tab?

  • Related