@wegasnpm/wegas-tracker-web
v1.0.5
Published
JavaScript utility library to dynamically load tracking script from WEGAS instance and track events with automatic page view tracking
Keywords
Readme
Wegas Tracker Web
A JavaScript utility library to dynamically load tracking script from WEGAS instance and track events with automatic page view tracking.
Features
- ✅ Dynamic Tracking script injection from WEGAS instances
- ✅ Automatic page view tracking for SPAs (Single Page Applications)
- ✅ Custom event tracking
- ✅ Promise-based API
- ✅ TypeScript support
- ✅ Works with React, Vue, Angular, and vanilla JavaScript
- ✅ UMD and ESM module support
Installation
npm install @wegasnpm/wegas-tracker-webUsage
ES6 Modules (Recommended)
import { initWegasTracker, sendPageview, trackEvent } from 'wegas-tracker-web';
// Initialize the tracker
await initWegasTracker({
baseUrl: 'https://your-wegas-instance.com',
disableTracking: boolean, // Complteley disable tracking
disablePageviewTracking: boolean, // Disable pageview tracking completely including manual pageview tracking
disableEventTracking: boolean, // Disable event tracking
customPageviewTracking: boolean, // Disable automatic pageview tracking and use manual pageview tracking by calling sendPageview()
});
// Send a custom pageview
await sendPageview({
url: '/custom-page',
title: 'Custom Page Title'
});
// Track custom events
await trackEvent('button_click', {
button_id: 'header-cta',
page: '/landing'
});
// Can be used to set the contact information for the current user.
// Example: You can set the contact information for the current user when the user logs in or registers.
await setWegasContact({
email: '[email protected]',
first_name: 'John',
last_name: 'Doe'
});
// Reset the contact information for the current user.
// Example: You can reset the contact information for the current user when the user logs out.
await resetWegasContact();CommonJS
const { initWegasTracker, sendPageview, trackEvent, setWegasContact, resetWegasContact } = require('wegas-tracker-web');
// Same API as aboveUMD (Browser)
<script src="https://unpkg.com/wegas-tracker-web/dist/wegas-tracking.umd.js"></script>
<script>
// Available as global wegasTracking
wegasTracking.initWegasTracker({
baseUrl: 'https://your-wegas-instance.com',
disableTracking: false,
disablePageviewTracking: false,
disableEventTracking: false,
customPageviewTracking: false
}).then(() => {
console.log('Tracker initialized!');
});
</script>API Reference
initWegasTracker(config)
Initialize the Wegas tracker with your WEGAS instance configuration.
Parameters:
config.baseUrl(string, required): The base URL of your WEGAS instanceconfig.disableTracking(boolean, optional): Completely disable trackingconfig.disablePageviewTracking(boolean, optional): Disable pageview trackingconfig.disableEventTracking(boolean, optional): Disable event trackingconfig.customPageviewTracking(boolean, optional): Disable automatic pageview tracking and use manual pageview tracking Returns:Promise<void>
Example:
await initWegasTracker({
baseUrl: 'https://your-wegas-instance.com',
disableTracking: false,
disablePageviewTracking: false,
disableEventTracking: false,
customPageviewTracking: false
});sendPageview(props?)
Send a pageview event to track page visits.
Parameters:
props(object, optional): Additional properties for the pageviewurl(string): Custom URL to tracktitle(string): Page title- Any other custom properties
Returns: Promise<void>
Example:
// Send current page
await sendPageview();
// Send custom page
await sendPageview({
url: '/custom-path',
title: 'Custom Page'
});trackEvent(event, data?, contact?, timestamp?)
Track custom events with optional data via the Wegas Events Plugin:
mt('send', eventName, eventData, contactData, timestampISO)
Event time is stored on Wegas’s tracked_events.timestamp (DATETIME) from the 5th mt() argument — not as an event property. Putting epoch milliseconds in data (e.g. { timestamp: Date.now() }) used to overflow MySQL value_integer (max 2147483647). This library now:
- Converts the optional
timestampargument (Date, epoch ms, or string) to an ISO string for the 5thmt()arg - Promotes any
data.timestampinto that same event timestamp (and removes it from properties) - Converts other out-of-range integers in
datato ISO datetime strings (epoch-ms) or strings (safe for Wegas storage)
Parameters:
event(string, required): Event namedata(object, optional): Event data/properties (do not put epoch-ms intimestamp; the SDK handles it)contact(object, optional): Contact informationtimestamp(number | string | Date, optional): Event time; converted to ISO and passed as the 5thmt()argument. Omit to let Wegas use “now”.
Returns: Promise<void>
Example:
// Preferred: omit timestamp — Wegas sets the event time
await trackEvent('purchase', {
product_id: 'abc123',
value: 29.99,
currency: 'USD'
}, { email: '[email protected]' });
// Optional override (Date.now() / Date / ISO string are all safe)
await trackEvent('purchase', {
product_id: 'abc123',
value: 29.99
}, { email: '[email protected]' }, Date.now());setWegasContact(contact)
Set the contact information for the current user. Example: You can set the contact information for the current user when the user logs in or registers.
Parameters:
contact(object, required): Contact information
Returns: Promise<void>
Example:
await setWegasContact({
email: '[email protected]',
first_name: 'John',
last_name: 'Doe'
});resetWegasContact()
Reset the contact information for the current user. Example: You can reset the contact information for the current user when the user logs out.
Returns: Promise<void>
Example:
await resetWegasContact();appLogin(contact, params?)
Track app login event.
Parameters:
contact(object, required): Contact informationparams(object, optional): Additional parameters
Returns: Promise<void>
Example:
await appLogin({
email: '[email protected]', // Required
});appLogout(contact, params?)
Track app logout event.
Parameters:
contact(object, optional): Contact informationparams(object, optional): Additional parameters
Returns: Promise<void>
Example:
await appLogout();Automatic Page Tracking
The library automatically tracks page changes in Single Page Applications (SPAs) by listening to:
history.pushState()history.replaceState()popstateevents
This means you don't need to manually call sendPageview() for navigation in React Router, Vue Router, etc.
You can disable automatic page tracking by setting disablePageviewTracking to true in the initWegasTracker() function. d
TypeScript Support
The library includes TypeScript definitions:
interface WegasConfig {
baseUrl: string;
disableTracking?: boolean;
disablePageviewTracking?: boolean;
disableEventTracking?: boolean;
customPageviewTracking?: boolean;
}
interface PageviewProps {
url?: string;
title?: string;
[key: string]: any;
}
declare function initWegasTracker(config: WegasConfig): Promise<void>;
declare function sendPageview(props?: PageviewProps): Promise<void>;
declare function trackEvent(
event: string,
data?: Record<string, any>,
contact?: any,
timestamp?: number | string | Date
): Promise<void>;
declare function setWegasContact(contact: any): Promise<void>;
declare function resetWegasContact(): Promise<void>;
declare function appLogin(contact: any, params?: any): Promise<void>;
declare function appLogout(contact: any, params?: any): Promise<void>;Error Handling
The library provides helpful error messages:
try {
await initWegasTracker({
baseUrl: 'https://your-wegas-instance.com',
});
} catch (error) {
console.error('Failed to initialize tracker:', error.message);
}Browser Compatibility
- Modern browsers with ES2017+ support
- Internet Explorer 11+ (with polyfills)
- Node.js 14+
Contributing
- Fork the repository
- Create your feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add some amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
License
MIT License. See LICENSE file for details.
