/**
* IMPORTANT: This pixel can only fire on sessions where the
* customer has a cart object, otherwise it will be skipped.
* For example, clicking "Buy Now" on a product page skips the cart,
* going directly to checkout.
**/
function processData({event, cartToken}) {
// TODO: Edit MYSHOPIFY_DOMAIN to your domain. E.g.
// const MYSHOPIFY_DOMAIN = 'example-store.myshopify.com';
const MYSHOPIFY_DOMAIN = '';
const enableDebug = false;
// DO NOT EDIT PAST HERE
const SESSION_STORAGE_KEY = 'as-customer-trigger-data';
const HOST = 'https://start.aftersell.app';
if (!MYSHOPIFY_DOMAIN) {
if (enableDebug) {
console.log("UTM pixel didn't fire because of missing Shopify domain");
}
return;
}
if (!cartToken) {
if (enableDebug) {
console.log("UTM pixel didn't fire because of missing cart token");
}
}
let existingCustomerData = null;
try {
existingCustomerData = JSON.parse(
sessionStorage.getItem(SESSION_STORAGE_KEY) || 'null'
);
} catch (ignore) {
if (enableDebug) {
console.log("UTM pixel didn't fire because malformed user data json");
}
}
const allowedUrlParams = [
'utm_source',
'utm_medium',
'utm_campaign',
'utm_term',
'utm_id',
'utm_content',
];
const searchParams = new URLSearchParams(event.context.window.location.search);
let hasCustomerData = false;
const customerData = {};
for (const param of allowedUrlParams) {
const paramValue = searchParams.get(param) || existingCustomerData?.[param];
if (paramValue) {
hasCustomerData = true;
customerData[param] = paramValue;
}
}
if (hasCustomerData) {
sessionStorage.setItem(SESSION_STORAGE_KEY, JSON.stringify(customerData));
const postBody = {
shop: MYSHOPIFY_DOMAIN,
cartToken,
checkoutToken: event.data.checkout.token ?? undefined,
customerTriggerData: customerData,
};
if (enableDebug) {
console.log("UTM pixel fired with the following data:", postBody);
}
fetch(`\${HOST}/api/v1/storefrontSessions`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(postBody),
});
} else {
if (enableDebug) {
console.log("UTM pixel didn't fire because there was no data to send");
}
}
}
analytics.subscribe('checkout_started', (event) => {
// minimum realistic time between adding item to cart and clicking checkout
const COOKIE_POLLING_INTERVAL_MS = 500;
let currentCookieValue = getCookieValue({ cookie: document.cookie, cookieName: 'cart' });
processData({event, cartToken: currentCookieValue});
setInterval(() => {
const newCookieValue = getCookieValue({ cookie: document.cookie, cookieName: 'cart' });
if (newCookieValue !== currentCookieValue) {
currentCookieValue = newCookieValue;
processData({event, cartToken: newCookieValue});
}
}, COOKIE_POLLING_INTERVAL_MS);
});
function getCookieValue({ cookie, cookieName }) {
const cartCookieRegex = new RegExp(`^\${cookieName}=`);
const cartCookie = cookie
.split(';')
.map((val) => val.trim())
.find((val) => cartCookieRegex.test(val));
if (!cartCookie) return null;
const cartCookieValue = cartCookie.replace(`\${cookieName}=`, '');
return cartCookieValue;
}