Determine if a tab in Chrome is currently active or not using a browser extension

I am currently developing a Chrome extension that is designed to monitor the amount of time a user spends on a website (aka an activity tracker). My strategy involves capturing the active and inactive states of the tab in order to calculate the total time spent, but I am encountering difficulties with detecting when the tab becomes inactive.

//// background.js

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

The provided code snippet is what I am utilizing to obtain information about the current tab.

Since this is my inaugural attempt at creating an extension,...

Answer №1

Utilizing the api function chrome.tabs.onActivated

let url = ''
let 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
    // Begin timer when url is null
    } else {
        time = currentTime
        url = newUrl
    }
  });

To retrieve either the url or href using this api, use

chrome.tabs.get(tabId, (res) => {} )

Answer №2

In my opinion, one useful approach could be to utilize a map for storing all the visited URLs as keys and their activation times as values. If this solution doesn't meet your requirements, I apologize. However, I am confident that you can make use of it effectively. Do let me know if you encounter any issues:

let VisitedURLs = new Map();

let lastUpdatedTime, previousURL;

chrome.tabs.onUpdated.addListener(function(tabID, changeInfo, currentTab) {
  var url = changeInfo.url;

  if (!url) return;
  
  if (url !== previousURL) {
    
    if (lastUpdatedTime) {
      const elapsedTime = (new Date().getTime()) - lastUpdatedTime;
      
      if (!VisitedURLs.has(previousURL)) {
        VisitedURLs.set(previousURL, elapsedTime); // Set elapsed time if URL is new
      } else {
        VisitedURLs.set(previousURL, VisitedURLs.get(url) + elapsedTime); // Increment time for existing URL
      }
    }

    lastUpdatedTime = new Date().getTime();
    previousURL = url;
  }
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

I have a question about CSS selectors: How can I change the font color of a parent <li> element when the child

After struggling for hours, I'm finally throwing in the towel on this issue. I have an unordered list with no background at the top level and text color of #fff. When rolled over, the background turns #fff and the text color turns #000. The child ul ...

What is the best way to ensure that the texture is properly positioned when replacing textures in gltf format using Three.js?

Trying to dynamically change the texture of a glTF model using the `THREE.TextureLoader`, I successfully changed the color as expected. However, the texture pattern appeared distorted. Exploring web graphics for the first time, I modified a 3D model viewe ...

Unable to open drop-down menu in Bootstrap-select on ASP.NET web application by clicking

Currently, as I work on developing an ASP.NET web application, I find myself facing significant challenges in getting the bootstrap-select feature to function correctly. Despite browsing through various threads on SO for solutions, the problem remains unr ...

display the HTML form when the page is clicked

Trying to implement an onclick method for selecting form types. I have multiple form types available - example here Clicking on one submenu should open up the desired form type directly below the menu How can I dynamically load a form based on the select ...

The process of utilizing the override feature in the package.json file to make updates to child dependencies

There seems to be a vulnerability in the async package that I want to update to version 3.2.2. Here is the dependency tree if I use npm list async: └─┬ [email protected] └─┬ [email protected] └── [email protected] After referring t ...

Issue with importing a file using JQuery causing the click event to not function properly

I have a file named navigation.html located in a directory called IMPORTS <!-- Navigation --> <div class="navbar-inner"> <div class="container"> <button type="button" class="btn btn-navbar" data-toggle="collapse" data-ta ...

Utilize JavaScript to transform today's date into a Martian date

I am trying to convert the current date on Earth to the current date on Mars using the Earth Date to Martian Solar Longitude Converter available here. The code appears to calculate the Mars date correctly, but I seem to be missing something. If anyone can ...

What is the method for identifying the selected radio button that has been dynamically generated after clicking the submit button?

Despite this question being asked multiple times before, I am struggling to find a solution that fits my specific scenario. Initially, I have a static radio button that I create. The HTML code is as follows: <body> &l ...

The model is only loaded when I access the developer toolbar

Recently, I encountered an issue while working with a three.js mesh. Upon opening the webpage in Chrome or Firefox (I haven't tested it on IE), everything seemed fine but the canvas displaying the mesh did not appear. It was only after activating the ...

collapse each <b-collapse> when a button is clicked (initially shown)

I am facing an issue with a series of connected b-buttons and b-collapse, all initially set to be visible (open). My goal is to hide them all when a toggle from my parent.vue component is activated - so upon clicking a button in the parent component, I wa ...

Creating a password with two distinct numbers using regular expressions

In javascript I am struggling to create a password that meets the criteria of having at least eight characters, including two SEPARATE digits, one uppercase and one lowercase letter, as well as one special character (-, @, #, $, &, *, +) but not /, !, ? ...

Adjusting the selection in the Dropdown Box

I've been attempting to assign a value to the select box as shown below: <dx-select-box [items]="reportingProject" id="ReportingProj" [text]="reportingProject" [readOnly]="true" > ...

Attempting to run a pair of JavaScript files simultaneously using the window.onload event

I'm facing an issue where two JavaScript files linked to a single HTML document are conflicting with each other. It seems like the second JS file is always taking precedence over the first one. I suspect that this might be related to both files using ...

Having trouble configuring individual route files in Express JS

I'm having trouble separating my login route from the default app.js and route/index.js files. When I try to access localhost:3000/login, I keep getting a 404 Not Found error. I've searched on StackOverflow for similar questions and tried follow ...

I'm curious about how I can apply @media queries given that certain phones possess higher resolution than computers

There seems to be a common recommendation to utilize @media queries for adjusting CSS based on whether the user is on mobile or not. However, I'm a bit confused because my phone has a width of 1440p while my computer has 1920p. Should I consider apply ...

Ways to Access Python List in JavaScript within a Django Template

I am currently working in oTree, a Django based environment for social experiments. I have encountered an issue while attempting to import lists from Python into an HTML template for use in Javascript. Although I can successfully display the lists in HTML ...

The Angular application must remain logged in until it is closed in the browser

Currently, my Angular app includes authentication functionality that is working smoothly. The only issue is that the application/session/token expires when there is no user activity and the app remains open in the browser. I am looking for a solution wher ...

How can I customize the styling of Autocomplete chips in MUI ReactJS?

Trying to customize the color of the MUI Autocomplete component based on specific conditions, but struggling to find a solution. Any ideas? https://i.stack.imgur.com/50Ppk.png ...

What is the best way to save a beloved pet for a user who is signed in?

Is there a way to store a favorite pet for a logged-in user using React and Express? I am currently retrieving pets from an API and using PostgreSQL as the database. const favPetDetails = { id, name, media, breeds, location, dista ...

Having trouble with blockUI compatibility on Internet Explorer 11?

I have encountered an issue with a piece of code that functions correctly in Chrome and FF, but not in ie11. Interestingly enough, when I tested it in ie8, it worked perfectly fine. Has anyone else experienced similar problems with blockUI on ie11? The s ...