npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, πŸ‘‹, I’m Ryan HefnerΒ  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you πŸ™

Β© 2026 – Pkg Stats / Ryan Hefner

use-iframe-tracker

v1.0.24

Published

πŸ”’ A secure, iframe-based visitor tracking solution for modern web applications, with built-in protection against cross-site tracking and security vulnerabilities.

Readme

use-iframe-tracker

πŸ”’ A secure, iframe-based visitor tracking solution for modern web applications, with built-in protection against cross-site tracking and security vulnerabilities.

TypeScript Vitest MIT License

🌟 Features

  • πŸ›‘οΈ Secure by default with CSP, sandbox policies, and permission restrictions
  • πŸ”„ Cross-origin and cross-tab session synchronization
  • 🎯 Configurable cookie and storage management
  • πŸš€ Lightweight and performant implementation
  • 🧩 Easy integration with any web application
  • πŸ”’ SameSite cookie protection
  • 🌐 Domain-specific cookie configuration
  • ⚑ Automatic token generation using crypto.randomUUID()
  • πŸ”„ Fallback mechanisms for token storage
  • 🎭 Parent-frame synchronization options

πŸ“¦ Installation

npm install use-iframe-tracker
# or
yarn add use-iframe-tracker

πŸš€ Quick Start

import HtmlTracker from 'use-iframe-tracker';

// Initialize with minimal configuration
const tracker = new HtmlTracker({
	iframeUrl: 'https://your-domain.com/iframe'
});

// Add the tracker iframe to your page
const iframeHtml = tracker.iframe();
// Add the tracker script to your page
const trackerScript = tracker.js();

πŸ› οΈ Configuration

type TrackerConfig = {
	checkInterval?: number; // Storage check interval (default: 1000ms)
	cookieName?: string; // Cookie name (default: 'visitor_token')
	domain?: string; // Cookie domain
	iframeUrl: string; // Base URL for the tracker iframe
	javascriptKey?: string; // Key for the javascript variable (default: 'visitor_token')
	sameSite?: 'Strict' | 'Lax' | 'None'; // SameSite cookie policy (default: 'None')
	secure?: boolean; // Use secure cookies (default: true)
	storageKey?: string; // localStorage key (default: 'visitor_token')
	syncWithParent?: boolean; // Enable parent frame sync (default: false)
};

☁️ Cloudflare Workers Integration

import HtmlTracker from 'use-iframe-tracker';

export default {
	async fetch(request: Request, env: Env, ctx: ExecutionContext) {
		const url = new URL(request.url);

		// Initialize tracker with your configuration
		const tracker = new HtmlTracker({
			iframeUrl: 'https://your-worker-domain.com/iframe',
			secure: true,
			sameSite: 'None'
		});

		// Handle tracker endpoints
		switch (url.pathname) {
			case '/iframe':
				// Serve the tracking iframe
				return new Response(tracker.iframe(), {
					headers: {
						'content-type': 'text/html',
						'cache-control': 'public, max-age=3600'
					}
				});

			case '/snippet.js':
				// Serve the tracking script
				return new Response(tracker.js(), {
					headers: {
						'content-type': 'application/javascript',
						'cache-control': 'public, max-age=3600'
					}
				});

			default:
				return new Response('Not Found', { status: 404 });
		}
	}
};

🌐 Deploy to Cloudflare

  1. Create a new Worker in your Cloudflare dashboard
  2. Configure your routes (e.g., tracker.your-domain.com/*)
  3. Deploy the code using Wrangler:
wrangler deploy

πŸ’‘ Advanced Usage

Custom Token Storage

const tracker = new HtmlTracker({
	iframeUrl: 'https://your-domain.com/iframe',
	storageKey: 'custom_visitor_id',
	cookieName: 'custom_visitor_cookie'
});

Cross-Domain Tracking

const tracker = new HtmlTracker({
	iframeUrl: 'https://tracking.your-domain.com/iframe',
	domain: '.your-domain.com',
	sameSite: 'None',
	secure: true
});

πŸͺ Cookie Configuration

Basic Cookie Setup

const tracker = new HtmlTracker({
	iframeUrl: 'https://your-domain.com/iframe',
	cookieName: 'visitor_id', // Custom cookie name (default: 'visitor_token')
	domain: '.your-domain.com', // Cookie domain (optional)
	secure: true, // Use secure cookie (default: true)
	sameSite: 'None' // SameSite policy (default: 'None')
});

Cookie Policies

The tracker handles different cookie configurations:

// Strict same-site policy (most secure)
const strictTracker = new HtmlTracker({
	iframeUrl: 'https://your-domain.com/iframe',
	sameSite: 'Strict',
	secure: true
});
// Results in: 'visitor_token=abc123; path=/; secure; samesite=Strict'

// Lax same-site policy (balanced)
const laxTracker = new HtmlTracker({
	iframeUrl: 'https://your-domain.com/iframe',
	sameSite: 'Lax'
});
// Results in: 'visitor_token=abc123; path=/; secure; samesite=Lax'

// Cross-domain tracking (least restrictive)
const crossDomainTracker = new HtmlTracker({
	iframeUrl: 'https://tracking.your-domain.com/iframe',
	domain: '.your-domain.com',
	sameSite: 'None' // Will force secure=true
});
// Results in: 'visitor_token=abc123; path=/; domain=.your-domain.com; secure; samesite=None'

Auto-Security Features

The tracker includes automatic cookie security features:

// SameSite=None automatically forces secure flag
const tracker = new HtmlTracker({
	iframeUrl: 'https://your-domain.com/iframe',
	sameSite: 'None',
	secure: false // Will be forced to true
});
// Console: "SameSite=None requires secure=true. Forcing secure=true."
// Results in: 'visitor_token=abc123; path=/; secure; samesite=None'

// Cross-domain with custom cookie
const customTracker = new HtmlTracker({
	iframeUrl: 'https://your-domain.com/iframe',
	cookieName: 'my_visitor',
	domain: '.your-domain.com',
	sameSite: 'None',
	secure: true
});
// Results in: 'my_visitor=abc123; path=/; domain=.your-domain.com; secure; samesite=None'

Cookie Persistence

The tracker maintains cookies across page loads and browser sessions:

// Cookie is automatically synchronized with localStorage
window.getVisitorToken().then(token => {
	// Check the cookie in browser dev tools:
	// Name: visitor_token (or your custom cookieName)
	// Value: auto-generated UUID or custom token
	// Domain: your configured domain
	// Path: /
	// SameSite: your configured policy
	// Secure: true if required
	console.log('Current token:', token);
});

Setup Your HTML

<!-- Add the tracking script to your page -->
<script src="https://your-domain.com/snippet.js"></script>

Using the Tracker APIs

// Get the current visitor token
window.getVisitorToken().then(token => {
	console.log('Visitor token:', token);
});

// Listen for token ready events
window.addEventListener('visitor:token-ready', event => {
	const { token, timestamp } = event.detail;
	console.log('Token is ready:', token);
	console.log('Timestamp:', new Date(timestamp));
});

Parent Frame Synchronization

Enable syncing between parent window and iframe:

// Server setup
const tracker = new HtmlTracker({
	iframeUrl: 'https://your-domain.com/iframe',
	syncWithParent: true,
	cookieName: 'my_visitor',
	storageKey: 'my_visitor_storage'
});

// In browser
// The token will automatically sync between iframe and parent
// You can listen for changes:
window.addEventListener('visitor:token-ready', event => {
	const { token, timestamp, source } = event.detail;
	console.log('Token updated from:', source);
	console.log('New token:', token);
});

// Force token refresh
window.getVisitorToken().then(token => {
	console.log('Current visitor token:', token);
});

Working with Custom Storage

The tracker provides multiple storage mechanisms that work together:

// Server setup
const tracker = new HtmlTracker({
	iframeUrl: 'https://your-domain.com/iframe',
	cookieName: 'custom_visitor', // Custom cookie name
	storageKey: 'custom_storage_key', // Custom localStorage key
	syncWithParent: true
});

// In browser
// The token is automatically stored in:
// 1. localStorage (using storageKey)
// 2. cookies (using cookieName)
// 3. memory (fallback)
// 4. parent window (if syncWithParent is true)

// The tracker automatically syncs between all storage methods
// and recovers from storage clearing

Security Features in Action

The tracker includes several security measures that work automatically:

// Secure origin checking
window.addEventListener('message', event => {
	// Messages from unauthorized origins are automatically rejected
	// You'll see a warning in the console:
	// "Rejected message from unauthorized origin: unauthorized-domain.com"
});

// CSP violations
// If the iframe's CSP is violated, you'll see warnings:
// "Refused to load frame from 'unauthorized-domain.com' because it violates the following Content Security Policy directive..."

// Cookie security
// SameSite=None cookies automatically force secure flag
// You'll see a warning if misconfigured:
// "SameSite=None requires secure=true. Forcing secure=true."

πŸ”’ Security Features

Content Security Policy

The tracker implements a strict CSP that:

  • Restricts resource loading to same origin
  • Allows only necessary inline scripts
  • Prevents unauthorized frame ancestors
  • Restricts base URI manipulation

Iframe Sandbox

Implements a secure sandbox policy allowing only:

  • Essential script execution
  • Same-origin communication

Permissions Policy

Restricts access to sensitive browser features:

  • Geolocation
  • Camera
  • Microphone
  • Payment APIs
  • USB access
  • And more...

🎯 Browser Support

  • βœ… Modern browsers with crypto.randomUUID() support
  • βœ… Fallback mechanisms for token generation
  • βœ… Cross-browser localStorage and cookie handling

πŸ§ͺ Testing

# Run the test suite
npm test
# or
yarn test

πŸ” Debugging

The tracker provides console warnings for:

  • Invalid security configurations
  • Cookie policy conflicts
  • Storage synchronization issues
  • Unauthorized message origins

🀝 Contributing

  1. Fork it
  2. Create your feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'feat: add amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

πŸ“ License

MIT Β© Felipe Rohde

⭐ Show your support

Give a ⭐️ if this project helped you!

πŸ‘¨β€πŸ’» Author

Felipe Rohde