Home > Net >  Chrome Extension detect if tab is active or inactive
Chrome Extension detect if tab is active or inactive

Time:12-24

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...

CodePudding user response:

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) => {} )

CodePudding user response:

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;
  }
});
  • Related