← back to Gmc Viewer
dw-ga4-custom-pixel.js
63 lines
// ─────────────────────────────────────────────────────────────
// DW GA4 Custom Pixel — G-53F1QBZSG0 (property 294178030 / acct 15714274)
// Shopify admin → Settings → Customer events → Add custom pixel →
// paste this whole block → Save → Connect.
// Handles the ECOMMERCE FUNNEL (view_item / add_to_cart / begin_checkout /
// purchase). Storefront page_views are already covered by the theme <head>
// gtag, so page_view is intentionally NOT sent here (avoids double-counting).
// ─────────────────────────────────────────────────────────────
const GA4_ID = 'G-53F1QBZSG0';
// Load gtag.js inside the pixel sandbox
const s = document.createElement('script');
s.src = 'https://www.googletagmanager.com/gtag/js?id=' + GA4_ID;
s.async = true;
document.head.appendChild(s);
window.dataLayer = window.dataLayer || [];
function gtag(){ dataLayer.push(arguments); }
gtag('js', new Date());
// send_page_view:false → the theme tag owns page_view; we only send ecommerce events
gtag('config', GA4_ID, { send_page_view: false });
const money = m => (m && m.amount != null) ? Number(m.amount) : undefined;
const cur = m => (m && m.currencyCode) || 'USD';
// Product viewed → view_item
analytics.subscribe('product_viewed', (e) => {
const v = e.data?.productVariant; if (!v) return;
gtag('event', 'view_item', {
currency: cur(v.price), value: money(v.price),
items: [{ item_id: v.sku || v.id, item_name: v.product?.title, item_variant: v.title, price: money(v.price) }]
});
});
// Add to cart → add_to_cart
analytics.subscribe('product_added_to_cart', (e) => {
const l = e.data?.cartLine; if (!l) return;
const m = l.merchandise;
gtag('event', 'add_to_cart', {
currency: cur(l.cost?.totalAmount), value: money(l.cost?.totalAmount),
items: [{ item_id: m?.sku || m?.id, item_name: m?.product?.title, item_variant: m?.title, quantity: l.quantity, price: money(m?.price) }]
});
});
// Checkout started → begin_checkout
analytics.subscribe('checkout_started', (e) => {
const c = e.data?.checkout; if (!c) return;
gtag('event', 'begin_checkout', {
currency: c.currencyCode, value: money(c.totalPrice),
items: (c.lineItems || []).map(li => ({ item_id: li.variant?.sku || li.variant?.id, item_name: li.title, quantity: li.quantity, price: money(li.variant?.price) }))
});
});
// Checkout completed → purchase (the money event)
analytics.subscribe('checkout_completed', (e) => {
const c = e.data?.checkout; if (!c) return;
gtag('event', 'purchase', {
transaction_id: c.order?.id || c.token,
currency: c.currencyCode, value: money(c.totalPrice),
tax: money(c.totalTax), shipping: money(c.shippingLine?.price),
items: (c.lineItems || []).map(li => ({ item_id: li.variant?.sku || li.variant?.id, item_name: li.title, quantity: li.quantity, price: money(li.variant?.price) }))
});
});