(async function() { document.addEventListener('DOMContentLoaded', () => { const addToCartButtons = document.querySelectorAll('[data-button-type="add-cart"]'); addToCartButtons.forEach(button => { button.addEventListener('click', (e) => { // Prevent the page from redirecting temporarily e.preventDefault(); // Get the full URL of the button's href (which contains the product_id and action) const fullUrl = button.href; // Trigger the trackCart function and pass the full URL trackCart(fullUrl); // Now, allow the redirect to happen after tracking window.location.href = fullUrl; }); }); }); // Function to get the user-agent const userAgent = navigator.userAgent; const observer = new PerformanceObserver((list, observer) => { const entries = list.getEntriesByType("resource"); entries.forEach(entry => { const url = new URL(entry.name); if (url.pathname.startsWith("/cart.php")) { trackCart(entry.name); } else if (url.pathname.includes("/api/storefront/checkouts/") && entry.initiatorType === "xmlhttprequest") { trackCheckout(entry.name); } }); }); // Start observing network requests observer.observe({ type: "resource", // Watch for resources like fetch, XHR, etc. buffered: true // Ensure we capture previous requests made on page load (if any) }); async function trackCart(fullUrl) { try { const cartResponse = await fetch('/api/storefront/cart', { method: 'GET', credentials: 'include', }); if (cartResponse.ok) { let cartData = await cartResponse.json(); await fetch('https://receiver.fero.com/v1/bigcommerce/conversion-iq', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ data: cartData, type: 'cart', user_agent: userAgent, shop: fullUrl.split('/')[2], triggered_at: new Date().toISOString() }) }); } } catch (error) { console.error('Error tracking cart:', error); } } async function trackCheckout(fullUrl) { try { const cartId = fullUrl.split('/')[6]; const url = `/api/storefront/checkouts/${cartId}`; const checkoutResponse = await fetch(url , { method: 'GET', credentials: 'include', }); if (checkoutResponse.ok) { let checkoutData = await checkoutResponse.json(); await fetch('https://receiver.fero.com/v1/bigcommerce/conversion-iq', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ data: checkoutData, type: 'checkout', user_agent: userAgent, shop: fullUrl.split('/')[2], triggered_at: new Date().toISOString() }) }); } } catch (error) { console.error('Error tracking checkout:', error); } } })();