The Palos Publishing Company

Follow Us On The X Platform @PalosPublishing
Categories We Write About

Create a browser tab usage tracker

Here is a JavaScript-based browser tab usage tracker that monitors when a user switches to or away from a specific tab, records the duration spent on the tab, and logs the total active time. This can be used in web apps to analyze user engagement.

html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Tab Usage Tracker</title> <style> body { font-family: Arial, sans-serif; margin: 2rem; } #log { margin-top: 1rem; white-space: pre-wrap; background: #f4f4f4; padding: 1rem; border-radius: 8px; } </style> </head> <body> <h1>Browser Tab Usage Tracker</h1> <p>This tracker logs the time you spend actively on this tab.</p> <div id="log"></div> <script> let activeStart = null; let totalTime = 0; const logEl = document.getElementById("log"); function log(message) { logEl.textContent += message + "n"; } function handleVisibilityChange() { if (document.visibilityState === "visible") { activeStart = Date.now(); log(`Tab focused at ${new Date(activeStart).toLocaleTimeString()}`); } else { if (activeStart) { const timeSpent = Date.now() - activeStart; totalTime += timeSpent; log(`Tab blurred at ${new Date().toLocaleTimeString()}`); log(`Time spent on tab: ${(timeSpent / 1000).toFixed(2)} seconds`); log(`Total active time: ${(totalTime / 1000).toFixed(2)} secondsn`); activeStart = null; } } } document.addEventListener("visibilitychange", handleVisibilityChange); window.addEventListener("beforeunload", () => { if (activeStart) { const timeSpent = Date.now() - activeStart; totalTime += timeSpent; log(`Session ending. Final time spent: ${(timeSpent / 1000).toFixed(2)} seconds`); } }); // Initial start if (document.visibilityState === "visible") { activeStart = Date.now(); log(`Initial tab focus at ${new Date(activeStart).toLocaleTimeString()}`); } </script> </body> </html>

Features:

  • Detects tab visibility using the visibilitychange event.

  • Records the time when the user switches to or away from the tab.

  • Logs total time spent on the tab.

  • Outputs time log directly in the browser for demonstration.

Deployment:

You can run this code in any HTML file in your browser, or integrate it into a web application to collect session behavior data.

Let me know if you’d like it to store data in localStorage, send it to a server, or run across multiple sessions.

Share this Page your favorite way: Click any app below to share.

Enter your email below to join The Palos Publishing Company Email List

We respect your email privacy

Categories We Write About