gtm-tracker-component
v1.0.0
Published
Reusable Lit web component for Google Tag Manager ecommerce tracking
Maintainers
Readme
GTM Tracker Component
A reusable Lit web component for Google Tag Manager ecommerce tracking that provides a generic interface for tracking view_item, add_to_cart, begin_checkout, and purchase events.
Features
- 🎯 Method-based API - Call specific methods programmatically for precise control
- 🔧 Generic Data Structure - Flexible e-commerce focused interfaces that work with any product type
- 🚫 Duplicate Prevention - Automatically prevents duplicate view_item events
- 📊 Event Dispatching - Emits custom events when GTM events are pushed
- 🐛 Debug Support - Methods to inspect and clear dataLayer for testing
- ⚡ Framework Agnostic - Works with Angular, React, Vue, or vanilla JavaScript
Installation
npm install
npm run buildUsage
Basic Setup
<!-- Include the component -->
<script type="module" src="./gtm-tracker.js"></script>
<!-- Add the component to your page (invisible) -->
<gtm-tracker id="gtmTracker"></gtm-tracker>JavaScript API
const tracker = document.getElementById('gtmTracker');
// Track a product view
tracker.pushViewItem({
products: [{
id: 'product-123',
name: 'Premium Widget',
category: 'Electronics',
price: 199.99,
brand: 'TechCorp'
}],
customer: {
email: '[email protected]'
}
});
// Track add to cart
tracker.pushAddToCart({
products: [{
id: 'product-123',
name: 'Premium Widget',
price: 199.99
}],
transaction: {
coupon: 'SAVE10'
}
});
// Track checkout
tracker.pushBeginCheckout({
products: [{
id: 'product-123',
name: 'Premium Widget',
price: 199.99
}],
transaction: {
coupon: 'SAVE10',
discountValue: 20.00,
serviceFee: 5.99,
billingCycle: 'Monthly'
}
});
// Track purchase
tracker.pushPurchase({
products: [{
id: 'product-123',
name: 'Premium Widget',
price: 199.99
}],
customer: {
email: '[email protected]'
},
transaction: {
id: 'transaction-456',
coupon: 'SAVE10',
discountValue: 20.00,
serviceFee: 5.99
}
});Angular Integration
// In your Angular service
export class GTMService {
private gtmTracker!: any;
ngAfterViewInit() {
this.gtmTracker = document.getElementById('gtmTracker');
}
trackQuoteView(quote: Quote) {
const data = {
products: [{
id: quote.quoteGuid,
name: 'Full Policy',
category: this.formatUpgrades(quote.upgrades),
category2: 'Pet Insurance',
category3: quote.petBreed,
category4: this.getPetAge(quote.petDob),
variant: quote.coverageType,
brand: 'YourBrand',
price: quote.monthlyPremium
}],
customer: {
email: quote.customer?.email
},
transaction: {
coupon: quote.partnerCode || 'No coupon'
}
};
this.gtmTracker?.pushViewItem(data);
}
trackPurchase(quote: Quote, policy: Policy) {
const data = {
products: this.formatQuoteProducts(quote),
customer: {
email: quote.customer?.email
},
transaction: {
id: policy.policyId,
coupon: quote.partnerCode || 'No coupon',
discountValue: quote.discounts || 0,
serviceFee: quote.serviceFee || 0,
billingCycle: 'Monthly'
}
};
this.gtmTracker?.pushPurchase(data);
}
}Data Interfaces
Product Interface
interface Product {
id: string; // Required: Unique product identifier
name: string; // Required: Product name
category?: string; // Optional: Primary category
category2?: string; // Optional: Secondary category
category3?: string; // Optional: Tertiary category
category4?: string; // Optional: Quaternary category
variant?: string; // Optional: Product variant
brand?: string; // Optional: Product brand
affiliation?: string; // Optional: Partner/affiliate
price: number; // Required: Product price
quantity?: number; // Optional: Quantity (default: 1)
}Customer Interface
interface Customer {
email?: string; // Optional: Customer email
id?: string; // Optional: Customer ID
}Transaction Interface
interface Transaction {
id?: string; // Optional: Transaction ID (required for purchase)
coupon?: string; // Optional: Coupon code
discountValue?: number; // Optional: Discount amount
serviceFee?: number; // Optional: Service fee
billingCycle?: string; // Optional: Billing cycle
}EcommerceData Interface
interface EcommerceData {
products: Product[]; // Required: Array of products
customer?: Customer; // Optional: Customer information
transaction?: Transaction; // Optional: Transaction details
currency?: string; // Optional: Currency (default: 'USD')
language?: string; // Optional: Language (default: 'en')
}Component Properties
<gtm-tracker
default-currency="USD"
default-language="en"
default-brand="YourBrand"
default-affiliation="No Partner"
default-coupon="No coupon">
</gtm-tracker>Event Listening
The component dispatches custom events when GTM events are pushed:
document.addEventListener('gtm-event-pushed', (event) => {
console.log('GTM Event:', event.detail.event);
console.log('Data:', event.detail.data);
});Methods
pushViewItem(data: EcommerceData)- Track product/service viewpushAddToCart(data: EcommerceData)- Track add to cart actionpushBeginCheckout(data: EcommerceData)- Track checkout initiationpushPurchase(data: EcommerceData)- Track completed purchaseresetViewItemTracking()- Reset duplicate prevention for view_itemgetDataLayer()- Get current dataLayer contents (debugging)clearDataLayer()- Clear dataLayer contents (debugging)
Examples
See example.html for complete working examples including:
- Pet insurance quote tracking
- Generic product tracking
- Multiple product scenarios
- Real-time dataLayer inspection
Browser Support
- Modern browsers supporting ES2021
- Custom Elements v1
- ES Modules
Development
# Install dependencies
npm install
# Build the component
npm run build
# Watch for changes
npm run dev
# Serve example
npm run serveLicense
MIT
