Comprehensive browser monitoring script that captures everything happening in a browser tab and forwards it to a configurable webhook URL
npm install pagewire




A comprehensive browser monitoring library with React hooks and components for seamless integration. Captures everything happening in a browser tab and forwards it to a configurable webhook URL via POST requests.
๐ React + Vite Ready โ Drop-in components, hooks, TypeScript support, and environment-based configuration.
1. Console โ Intercept all console methods (log, warn, error, info, debug, trace) while preserving original output
2. Network โ Monitor XMLHttpRequest and fetch API calls with method, URL, status, timing, and response data
3. Errors โ Capture JavaScript errors, unhandled promise rejections, syntax errors, and resource loading failures
4. Performance โ Page load timing, resource timing, Core Web Vitals (LCP, FID, CLS), Long Tasks via PerformanceObserver
5. DOM Mutations โ Summarized element additions, removals, and attribute changes via MutationObserver
6. User Interactions โ Clicks, scroll events, form inputs, keyboard shortcuts with target element information
7. Navigation โ URL changes, hash changes, pushState/replaceState interception for SPA routing
8. WebSocket โ Complete WebSocket lifecycle monitoring (connect, message, close, error events)
9. Storage โ localStorage and sessionStorage change detection
10. Visibility โ Tab focus/blur, page visibility changes, beforeunload events
11. CSP Violations โ SecurityPolicyViolationEvent monitoring
12. Deprecation/Intervention Warnings โ ReportingObserver integration
13. Memory โ Periodic performance.memory snapshots (Chrome only)
14. Cookie Changes โ Via cookieStore API with polling fallback
- React Integration โ Hooks, providers, and components for modern React apps
- Vite Optimized โ Environment variables, SSR detection, development mode support
- TypeScript Ready โ Full type definitions included
- Single IIFE โ Self-contained, no external dependencies
- Function-based initialization โ Configure via initPageWire(config) function
- Event batching โ Flushes events every 5 seconds (configurable)
- Smart delivery โ Uses sendBeacon for reliable delivery on page unload
- Unique session tracking โ Generated session ID per page load
- Performance optimized โ Throttling/debouncing for noisy events
- Error resilient โ Comprehensive try/catch blocks prevent page breakage
- Category toggles โ Easy enable/disable for each monitoring type
- Memory efficient โ Capped buffer size with circular reference handling
- Global kill switch โ stopBrowserMonitoring() function for cleanup
``bash`
npm install pagewireReact 16.8+ required for hooks
`bash`
npm install pagewire
`html`
Download browser-monitor.js from the GitHub repository.
`jsx
// 1. Install
npm install pagewire
// 2. Add to your main App component
import { PageWireProvider } from 'pagewire/react';
function App() {
return (
webhookUrl: import.meta.env.VITE_PAGEWIRE_WEBHOOK_URL,
categories: { errors: true, performance: true }
}}
>
);
}
// 3. Add to your .env file
VITE_PAGEWIRE_WEBHOOK_URL=https://your-webhook.example.com/events
`
#### Option 1: Direct Script Include
`html`
#### Option 2: React Integration
`jsx
import { PageWireProvider } from 'pagewire/react';
function App() {
return (
webhookUrl: 'https://your-webhook.example.com/events'
}}
>
);
}
`
#### Option 3: npm + Bundler (Webpack, Vite, etc.)
`javascript
import { getScriptWithConfig } from 'pagewire';
// Get the script with configuration
const script = getScriptWithConfig('https://your-webhook.example.com/events');
// Inject into page (method varies by framework)
const scriptEl = document.createElement('script');
scriptEl.textContent = script;
document.head.appendChild(scriptEl);
`
#### Express.js Middleware
`javascript
const { expressMiddleware } = require('pagewire');
app.use(expressMiddleware('https://your-webhook.example.com/events', {
categories: { performance: false, memory: false }
}));
`
#### Manual Script Generation
`javascript
const pagewire = require('pagewire');
// Get raw script
const script = pagewire.getScript();
// Get script with config
const configuredScript = pagewire.getScriptWithConfig('https://webhook.com/events');
// Get complete script tag
const scriptTag = pagewire.getScriptTag('https://webhook.com/events', {
flushInterval: 10000
});
`
`javascript
// Basic configuration
initPageWire({
webhookUrl: 'https://your-webhook.example.com/events'
});
// Advanced configuration
initPageWire({
webhookUrl: 'https://your-webhook.example.com/events',
flushInterval: 10000, // Flush every 10 seconds
categories: {
console: true,
network: true,
errors: true,
performance: false, // Disable performance monitoring
userInteractions: true
},
throttle: {
scroll: 500, // Throttle scroll events to every 500ms
memoryCheck: 60000 // Check memory every minute
}
});
`
โ ๏ธ Important: You must provide a webhookUrl or the script will throw an error:
`javascript
// This will throw an error
initPageWire({}); // Error: webhookUrl is required
// This works
initPageWire({
webhookUrl: 'https://your-webhook.com/events'
});
`
If you don't initialize within 3 seconds, you'll see an error message:
``
PageWire: Not initialized. Call initPageWire({ webhookUrl: "https://your-webhook.com/events" }) to start monitoring.
`javascript`
// Call this function to stop all monitoring and clean up
stopBrowserMonitoring();
Pass any of these options to initPageWire(config):
`javascript`
initPageWire({
webhookUrl: 'https://your-webhook.example.com/events', // Required
flushInterval: 5000, // Flush events every 5 seconds
maxBufferSize: 1000, // Maximum events before force flush
// Enable/disable categories
categories: {
console: true,
network: true,
errors: true,
performance: true,
domMutations: true,
userInteractions: true,
navigation: true,
webSocket: true,
storage: true,
visibility: true,
cspViolations: true,
deprecationWarnings: true,
memory: true,
cookieChanges: true
},
// Throttling/debouncing settings
throttle: {
scroll: 250, // Scroll events every 250ms
mousemove: 100, // Mouse events every 100ms
domMutations: 500, // DOM mutation summaries every 500ms
memoryCheck: 30000 // Memory snapshots every 30 seconds
}
});
You only need to specify the options you want to override:
`javascript
// Minimal configuration - just set webhook URL
initPageWire({
webhookUrl: 'https://api.mysite.com/monitor'
});
// Disable some categories
initPageWire({
webhookUrl: 'https://api.mysite.com/monitor',
categories: {
performance: false, // Disable performance monitoring
memory: false, // Disable memory monitoring
domMutations: false // Disable DOM mutation tracking
}
});
// Custom throttling
initPageWire({
webhookUrl: 'https://api.mysite.com/monitor',
throttle: {
scroll: 1000, // Less frequent scroll events
memoryCheck: 60000 // Check memory every minute
}
});
`
Each event sent to your webhook follows this structure:
`javascript`
{
"timestamp": 1640995200000,
"sessionId": "session_1234567890_abc123def",
"category": "console",
"type": "log",
"data": {
"arguments": ["Hello world", "Debug info"],
"stack": "Error\n at Object.log..."
},
"url": "https://example.com/page",
"userAgent": "Mozilla/5.0..."
}
javascript
{
"category": "console",
"type": "error",
"data": {
"arguments": ["Error message", errorObject],
"stack": "Error stack trace"
}
}
`$3
`javascript
{
"category": "network",
"type": "fetch_complete",
"data": {
"method": "POST",
"url": "https://api.example.com/data",
"status": 200,
"duration": 145.2,
"responseSize": 1024
}
}
`$3
`javascript
{
"category": "userInteractions",
"type": "click",
"data": {
"tagName": "BUTTON",
"id": "submit-btn",
"className": "btn btn-primary",
"x": 150,
"y": 200
}
}
`$3
`javascript
{
"category": "performance",
"type": "lcp",
"data": {
"value": 1250.5,
"element": "IMG"
}
}
`Webhook Integration
Your webhook endpoint should accept POST requests with JSON payloads containing arrays of events:
`javascript
// Example Express.js webhook handler
app.post('/events', (req, res) => {
const events = req.body; // Array of event objects
events.forEach(event => {
console.log([${event.category}] ${event.type}:, event.data);
// Process, store, or forward the event data
});
res.status(200).send('OK');
});
`Browser Compatibility
- Modern browsers โ Full feature support (Chrome 60+, Firefox 55+, Safari 12+)
- Legacy browsers โ Graceful degradation with basic monitoring
- Mobile browsers โ Full support on iOS Safari and Chrome Mobile
Security Considerations
- No sensitive data capture โ Passwords and secure fields are excluded
- Configurable categories โ Disable monitoring types as needed
- Safe serialization โ Handles circular references and large objects
- Error isolation โ Monitoring failures won't break your application
Use Cases
$3
- โ๏ธ Component Error Tracking โ Monitor React component errors and lifecycle issues
- ๐ฏ User Journey Analysis โ Track navigation patterns in SPAs
- ๐ฅ Development Debugging โ Real-time error monitoring during development
- ๐ Performance Monitoring โ React re-render tracking and Core Web Vitals
- ๐งช A/B Testing โ Monitor user interactions across different React variants
- ๐ก๏ธ Production Monitoring โ Environment-specific error tracking$3
- Debugging โ Monitor user actions leading to errors
- Performance analysis โ Track real user metrics and Core Web Vitals
- User behavior analytics โ Understand how users interact with your site
- Error tracking โ Comprehensive error monitoring and reporting
- Security monitoring โ CSP violations and suspicious activity detection
- A/B testing โ Monitor user interactions across different variantsReact Integration
$3
PageWire provides React-specific components and hooks for seamless integration with React applications, especially those using Vite.
#### usePageWire Hook
`jsx
import { usePageWire } from 'pagewire/react';function MyComponent() {
const { isInitialized, error, restart, stop } = usePageWire({
webhookUrl: 'https://your-webhook.example.com/events',
categories: {
console: true,
network: true,
errors: true
}
});
if (error) {
return
Error: {error};
} return (
Status: {isInitialized ? 'Monitoring' : 'Loading...'}
);
}
`#### PageWireProvider Component
`jsx
import { PageWireProvider, usePageWireContext } from 'pagewire/react';function App() {
return (
config={{
webhookUrl: 'https://your-webhook.example.com/events',
categories: { errors: true, performance: true }
}}
onError={(error) => console.error('PageWire error:', error)}
onInitialized={() => console.log('PageWire ready')}
>
);
}
function MyApp() {
const { isInitialized, config } = usePageWireContext();
return
App content - Monitoring: {isInitialized};
}
`#### Environment-based Configuration (Vite)
`jsx
import { PageWireMonitor } from 'pagewire/react';function App() {
return (
enabled={import.meta.env.PROD} // Only in production
config={{
webhookUrl: import.meta.env.VITE_PAGEWIRE_WEBHOOK_URL,
categories: {
console: import.meta.env.DEV, // Console logs only in dev
errors: true,
performance: true,
userInteractions: import.meta.env.PROD,
network: true
},
flushInterval: import.meta.env.DEV ? 2000 : 5000 // More frequent in dev
}}
>
);
}
`#### Vite Environment Variables
Create these files in your project root:
.env.development
`bash
VITE_PAGEWIRE_WEBHOOK_URL=http://localhost:3001/dev-events
`.env.production
`bash
VITE_PAGEWIRE_WEBHOOK_URL=https://api.yourapp.com/analytics/events
`.env.local (git-ignored, for local overrides)
`bash
VITE_PAGEWIRE_WEBHOOK_URL=https://your-dev-webhook.ngrok.io/events
`#### TypeScript Support
`tsx
import { PageWireConfig } from 'pagewire/react';const config: PageWireConfig = {
webhookUrl: 'https://your-webhook.example.com/events',
categories: {
console: true,
network: true,
errors: true
}
};
`$3
- ๐ SSR Safe โ Automatically detects server-side rendering
- ๐งน Automatic Cleanup โ Handles component unmounting
- ๐ก๏ธ Error Boundaries โ Graceful error handling
- ๐ก Context API โ Share configuration across components
- ๐ Environment Support โ Vite environment variables, development vs production
- ๐ TypeScript โ Full type definitions included
- โก Vite Optimized โ Works seamlessly with Vite's dev server and build process
- ๐ฅ Hot Reload Compatible โ Properly handles Vite's hot module replacement
API Reference
$3
`javascript
const pagewire = require('pagewire');
`####
getScript(): string
Returns the raw browser monitoring script as a string.####
getScriptWithConfig(webhookUrl, config?): string
Returns the script with pre-configured initialization.
- webhookUrl (string, required): Your webhook URL
- config (object, optional): Additional configuration options####
getScriptTag(webhookUrl, config?): string
Returns a complete