top of page
bottom of page
// Initialize the Data Layer
window.dataLayer = window.dataLayer || [];
// Function to push events to the Data Layer
function trackEvent(eventType, eventDetails) {
window.dataLayer.push({
event: eventType,
...eventDetails // Add dynamic details for each event
});
}
// Helper function to extract product details dynamically
function getProductDetails() {
try {
const productId = document.querySelector('[data-product-id]')?.getAttribute('data-product-id') || 'unknown';
const productName = document.querySelector('.product-name')?.innerText || 'Unknown Product';
const productPrice = parseFloat(document.querySelector('.product-price')?.innerText.replace(/[^0-9.]/g, '')) || 0;
return {
content_ids: [productId],
content_name: productName,
value: productPrice,
currency: "INR"
};
} catch (error) {
console.error("Error fetching product details: ", error);
return {};
}
}
// Helper function to extract checkout or purchase details
function getCheckoutDetails() {
try {
const items = [];
document.querySelectorAll('.cart-item').forEach(item => {
const id = item.getAttribute('data-product-id');
const name = item.querySelector('.cart-item-name')?.innerText;
const price = parseFloat(item.querySelector('.cart-item-price')?.innerText.replace(/[^0-9.]/g, '')) || 0;
const quantity = parseInt(item.querySelector('.cart-item-quantity')?.innerText) || 1;
items.push({ id, name, price, quantity });
});
const totalValue = items.reduce((sum, item) => sum + item.price * item.quantity, 0);
return {
content_ids: items.map(item => item.id),
products: items,
value: totalValue,
currency: "INR"
};
} catch (error) {
console.error("Error fetching checkout details: ", error);
return {};
}
}
// Dynamic tracking based on URL path
(function() {
const path = window.location.pathname;
// Track PageView for every page
trackEvent('PageView', { page_path: path });
// Home Page Tracking
if (path === "/") {
trackEvent('ViewContent', { page_type: "HomePage", currency: "INR" });
}
// Product Page Tracking
if (path.includes("product")) {
const productDetails = getProductDetails();
trackEvent('ViewContent', {
...productDetails,
content_type: "product"
});
}
// Add to Cart Tracking
if (path.includes("cart")) {
const cartDetails = getCheckoutDetails();
trackEvent('AddToCart', {
...cartDetails,
quantity: 1 // Total cart quantity can be adjusted dynamically
});
}
// Initiate Checkout Tracking
if (path.includes("checkout")) {
const checkoutDetails = getCheckoutDetails();
trackEvent('InitiateCheckout', {
...checkoutDetails,
content_type: "product"
});
}
// Purchase Tracking
if (path.includes("thank-you")) {
const purchaseDetails = getCheckoutDetails();
trackEvent('Purchase', {
transaction_id: "ORDER_" + new Date().getTime(), // Replace with dynamic transaction ID if available
...purchaseDetails
});
}
})();