Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

227
Views
Chrome Extension detect if tab is active or inactive

I am trying to create a Chrome extension which will track the time a user used a website (i.e, an activity tracker) my approach is to get the time when the tab is active and get the time when inactive then subtract, but i can't get the inactive tab

//// background.js

async function getCurrentTab() {
  let queryOptions = { active: true, currentWindow: true };
  let [tab] = await chrome.tabs.query(queryOptions);
  return tab;
}

this is the code I am using to get the current tab info

this is my first extension so...

about 4 years ago · Santiago Trujillo
2 answers
Answer question

0

Using api chrome.tabs.onActivated

const url = ''
const time = 0

chrome.tabs.onActivated.addListener(async (activeInfo) => {
    const { tabId } = activeInfo;
      
    const newUrl = tabId
    const currentTime = new Date().getTime()

    if (url && url !== newUrl) {
        const elapsedTime = currentTime - time;
        time = new Date().getTime()
        url = newUrl
    // 1. if url is null, start timer
    } else {
        time = currentTime
        url = newUrl
    }
  });

If you want to get url or href using this api chrome.tabs.get(tabId, (res) => {} )

about 4 years ago · Santiago Trujillo Report

0

I believe you can use a map to store all the visited Url's as keys, and the time they have been activated as values. If this isn't what you are looking for, then I'm sorry but I'm sure you can use this? Tell me if something doesn't work:

let Opened = new Map();

let lastChanged, previousUrl;

chrome.tabs.onUpdated.addListener(function (tabid, changeInfo, tab) {
  var currentUrl = changeInfo.url;

  if (!currentUrl) return;

  if (currentUrl !== previousUrl) {

    if (lastChanged) {
      const elapsedTime = (new Date().getTime()) - lastChanged;

      if (!Opened.has(previousUrl)) {
        Opened.set(previousUrl, elapsedTime); // Set time to the elapsed time if its a new URL
      } else {
        Opened.set(previousUrl, Opened.get(currentUrl) + elapsedTime); // Increment the time for this URL
      }
    }

    lastChanged = new Date().getTime();
    previousUrl = currentUrl;
  }
});
about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!