
Security News
Axios Supply Chain Attack Reaches OpenAI macOS Signing Pipeline, Forces Certificate Rotation
OpenAI rotated macOS signing certificates after a malicious Axios package reached its CI pipeline in a broader software supply chain attack.
screen-time-track
Advanced tools
Library to measure the screen time of a user on each page. Works with vanilla JS, React, and any framework.
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.
pushState / replaceState navigation — each route is timed independentlycurrentPageTime — live HH:MM:SS timer that updates every second, no tab switch needed.d.ts typesuseScreenTime() with reactive statenpm install screen-time-tracker
The library automatically selects the best available storage driver — no setup required:
| Environment | Driver used |
|---|---|
| Modern browser | IndexedDB |
| Browser without IndexedDB | localStorage |
Server (SSR) / no window | In-memory (no persistence) |
{
url: "https://myapp.com/dashboard",
durations: [
{ visit: 1, time: 3200 }, // milliseconds
{ visit: 2, time: 8500 }
]
}
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'
Import the hook from the /react subpath. Place useScreenTime() at the top level of your app so tracking covers every route.
// App.tsx
import { useScreenTime } from 'screen-time-tracker/react';
export default function App() {
useScreenTime(); // one line — starts and stops automatically
return <Router />;
}
// 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:
currentPageTimeshows the live elapsed time for the page currently being visited.totalTimeshows the accumulated saved time from all previous sessions — it updates after each navigation or tab switch.
data — PageRecord[]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>
));
totalTime — Record<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>
));
currentPageTime — stringDirect 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', ...
currentPageTimeandtotalTimecomplement each other: usecurrentPageTimefor the live session andtotalTimefor the historical total.
isTracking — booleanDirect 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>
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/)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/)// 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.
ScreenTimeTracker| Method | Returns | Description |
|---|---|---|
startTracking() | void | Starts timing the current page |
stopTracking() | Promise<void> | Stops timing and saves the duration |
getElapsedTime() | number | Milliseconds 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) | void | Register 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() | void | Removes event listeners (call when unmounting in SPAs) |
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.tracker.stopTracking() before navigating and tracker.startTracking() on the new route. Use tracker.getElapsedTime() to read the live session duration without saving it.tracker.getStorageDriver() to verify the correct driver is being used in your environment.Contributions are welcome! Feel free to open issues or pull requests in the repository: screen-time-tracker
Screen Time Tracker is released under the MIT License.
⌨️ with ❤️ by TatanLion 😊
FAQs
Library to measure the screen time of a user on each page. Works with vanilla JS, React, and any framework.
We found that screen-time-track demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?

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.

Security News
OpenAI rotated macOS signing certificates after a malicious Axios package reached its CI pipeline in a broader software supply chain attack.

Security News
Open source is under attack because of how much value it creates. It has been the foundation of every major software innovation for the last three decades. This is not the time to walk away from it.

Security News
Socket CEO Feross Aboukhadijeh breaks down how North Korea hijacked Axios and what it means for the future of software supply chain security.