New Research: Supply Chain Attack on Axios Pulls Malicious Dependency from npm.Details
Socket
Book a DemoSign in
Socket

screen-time-track

Package Overview
Dependencies
Maintainers
1
Versions
2
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

screen-time-track

Library to measure the screen time of a user on each page. Works with vanilla JS, React, and any framework.

latest
Source
npmnpm
Version
2.0.0
Version published
Maintainers
1
Created
Source

Screen Time Tracker

A lightweight, framework-agnostic library to measure how long users spend on each page of your web application. Works out of the box with Vanilla JS, React (Vite), Next.js, and any other framework.

Tracking pauses automatically when the tab loses focus or is minimized, and resumes when the user comes back — no configuration needed.

Features

  • Automatic pause/resume on tab visibility change
  • SPA route-aware: detects pushState / replaceState navigation — each route is timed independently
  • currentPageTime — live HH:MM:SS timer that updates every second, no tab switch needed
  • Smart storage: IndexedDBlocalStoragein-memory (auto-detected)
  • Full TypeScript support with bundled .d.ts types
  • SSR-safe: does nothing on the server, no crashes in Next.js
  • React hook useScreenTime() with reactive state
  • Dual module output: ESM + CJS

Install

npm install screen-time-tracker

Storage Strategy

The library automatically selects the best available storage driver — no setup required:

EnvironmentDriver used
Modern browserIndexedDB
Browser without IndexedDBlocalStorage
Server (SSR) / no windowIn-memory (no persistence)

Data structure

{
  url: "https://myapp.com/dashboard",
  durations: [
    { visit: 1, time: 3200 },   // milliseconds
    { visit: 2, time: 8500 }
  ]
}

Usage: Vanilla JS

import { ScreenTimeTracker } from 'screen-time-tracker';

const tracker = new ScreenTimeTracker();

// Start tracking the current page
tracker.startTracking();

// Stop and save when the user leaves
window.addEventListener('beforeunload', () => tracker.stopTracking());

// Get total time per page (HH:MM:SS)
const times = await tracker.calculateTotalTime();
console.log(times);
// { 'https://myapp.com/home': '00:02:30', 'https://myapp.com/about': '00:01:05' }

// Get time for a specific URL
const time = await tracker.getPageTime('https://myapp.com/home');
console.log(time); // '00:02:30'

// Export all raw data as JSON string
const json = await tracker.exportData();

// React to every save event
tracker.onSave((record) => {
  console.log('Saved:', record.url, record.durations);
});

// Clear all stored data
await tracker.reset();

// Check which storage driver is active
console.log(tracker.getStorageDriver()); // 'indexeddb' | 'localstorage' | 'memory'

Usage: React (Vite)

Import the hook from the /react subpath. Place useScreenTime() at the top level of your app so tracking covers every route.

Basic — tracking only

// App.tsx
import { useScreenTime } from 'screen-time-tracker/react';

export default function App() {
  useScreenTime(); // one line — starts and stops automatically

  return <Router />;
}

With data and controls

// Dashboard.tsx
import { useScreenTime } from 'screen-time-tracker/react';

export default function Dashboard() {
  const { data, totalTime, currentPageTime, isTracking, exportData, reset } = useScreenTime();

  return (
    <div>
      <h1>Time per page</h1>

      {/* Live timer for the current page — updates every second */}
      <p>Time on this page: {currentPageTime}</p>

      {/* Persisted totals for all visited pages */}
      <ul>
        {data.map((page) => (
          <li key={page.url}>
            <strong>{page.url}</strong> — {totalTime[page.url]}
          </li>
        ))}
      </ul>

      <p>Status: {isTracking ? 'Active' : 'Paused'}</p>

      <button onClick={exportData}>Export JSON</button>
      <button onClick={reset}>Clear data</button>
    </div>
  );
}

Note: currentPageTime shows the live elapsed time for the page currently being visited. totalTime shows the accumulated saved time from all previous sessions — it updates after each navigation or tab switch.

Hook return values

dataPageRecord[]

Direct value, no Promise. An array with one entry per visited URL. Each entry contains the URL and an array of individual visit durations in milliseconds.

const { data } = useScreenTime();

// Each PageRecord looks like:
// { url: 'https://myapp.com/home', durations: [{ visit: 1, time: 3200 }, { visit: 2, time: 8500 }] }

data.map(page => (
  <p key={page.url}>
    {page.url} — {page.durations.length} visit(s)
  </p>
));

totalTimeRecord<string, string>

Direct value, no Promise. An object where each key is a URL and each value is the total accumulated time in HH:MM:SS. This value is persisted — it updates after each navigation or tab switch, not in real time.

const { totalTime } = useScreenTime();

// Read time for a specific page
const homeTime = totalTime['https://myapp.com/home']; // e.g. '00:02:30'

// Render all pages
Object.entries(totalTime).map(([url, time]) => (
  <p key={url}>{url}: {time}</p>
));

currentPageTimestring

Direct value, no Promise. A live HH:MM:SS string that updates every second while the user is on the current page. It reflects the active session that has not been saved yet — it resets to '00:00:00' on each route change.

const { currentPageTime } = useScreenTime();

// Use it as a live ticker
<p>Time on this page: {currentPageTime}</p> // '00:00:45', '00:00:46', ...

currentPageTime and totalTime complement each other: use currentPageTime for the live session and totalTime for the historical total.

isTrackingboolean

Direct value, no Promise. true when the tracker is actively counting time; false when paused (tab hidden or minimized).

const { isTracking } = useScreenTime();

<span>{isTracking ? '🟢 Active' : '🔴 Paused'}</span>

exportData() => Promise<string>

A function that returns a Promise. Calling it resolves with all stored records serialized as a formatted JSON string. Useful for debugging or sending data to an analytics endpoint.

const { exportData } = useScreenTime();

// With async/await
const json = await exportData();
console.log(json);
// [
//   { "url": "https://myapp.com/home", "durations": [...] },
//   ...
// ]

// Or with .then()
<button onClick={() => exportData().then(console.log)}>Export</button>

reset() => Promise<void>

A function that returns a Promise. Clears all stored data from IndexedDB/localStorage and resets data, totalTime and currentPageTime back to their initial empty state.

const { reset } = useScreenTime();

// With async/await
await reset();

// Or directly on a button
<button onClick={reset}>Clear all data</button>

Usage: Next.js

IndexedDB and window do not exist on the server. The library handles this automatically — it simply does nothing during SSR and activates on the client.

App Router (app/)

Add 'use client' to any component that uses the hook or the class directly.

// app/layout.tsx
import Tracker from '@/components/Tracker';

export default function RootLayout({ children }: { children: React.ReactNode }) {
  return (
    <html>
      <body>
        <Tracker />
        {children}
      </body>
    </html>
  );
}
// components/Tracker.tsx
'use client';

import { useScreenTime } from 'screen-time-tracker/react';

export default function Tracker() {
  useScreenTime(); // tracking starts here, safe on server
  return null;
}

Pages Router (pages/)

// pages/_app.tsx
import { useScreenTime } from 'screen-time-tracker/react';
import type { AppProps } from 'next/app';

export default function MyApp({ Component, pageProps }: AppProps) {
  useScreenTime();
  return <Component {...pageProps} />;
}

Tip: In Next.js the hook detects SSR automatically — no need to wrap it in typeof window !== 'undefined' checks.

Full API Reference — ScreenTimeTracker

MethodReturnsDescription
startTracking()voidStarts timing the current page
stopTracking()Promise<void>Stops timing and saves the duration
getElapsedTime()numberMilliseconds elapsed in the current running session (0 if not tracking)
exportData()Promise<string>All records serialized as a JSON string
calculateTotalTime()Promise<Record<string, string>>Total saved time per URL in HH:MM:SS
getPageTime(url?)Promise<string>Saved time for one URL (defaults to current page)
getAllRecords()Promise<PageRecord[]>Raw records for all pages
onSave(callback)voidRegister a callback fired after each save
deleteIndexDB()Promise<void>Clears all stored data
reset()Promise<void>Alias for deleteIndexDB()
getStorageDriver()'indexeddb' | 'localstorage' | 'memory'Active storage driver
destroy()voidRemoves event listeners (call when unmounting in SPAs)

Tips

  • React Router / TanStack Router / Next.js App Router: place useScreenTime() in your root layout component so it mounts once and handles all route changes automatically.
  • totalTime vs currentPageTime: totalTime reflects persisted data (updated after each navigation); currentPageTime is the live ticker for the page you are on right now. Use both together for a complete picture.
  • Vanilla JS SPAs: call tracker.stopTracking() before navigating and tracker.startTracking() on the new route. Use tracker.getElapsedTime() to read the live session duration without saving it.
  • Testing: use tracker.getStorageDriver() to verify the correct driver is being used in your environment.
  • Privacy: all data is stored locally in the user's browser — nothing is sent to any server.

Contributing

Contributions are welcome! Feel free to open issues or pull requests in the repository: screen-time-tracker

License

Screen Time Tracker is released under the MIT License.

Authors ✒️

  • Jonathan Amaya - Systems Engineer - Full Stack Developer - TatanLion

⌨️ with ❤️ by TatanLion 😊

Keywords

time

FAQs

Package last updated on 12 Mar 2026

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts