Skip to content

Instantly share code, notes, and snippets.

@keiraarts
Created May 22, 2025 16:06
Show Gist options
  • Save keiraarts/d220e3d48ec43978320a739b506cf86e to your computer and use it in GitHub Desktop.
Save keiraarts/d220e3d48ec43978320a739b506cf86e to your computer and use it in GitHub Desktop.
<script>
document.addEventListener("DOMContentLoaded", initializeOnSiteJavascript);
function initializeOnSiteJavascript() {
// Track viewed products
const productId = "{{ product.id }}";
const productTitle = "{{ product.title }}";
const productHandle = "{{ product.handle }}";
const marketId = "{{ localization.market.id }}";
const trackViewedProducts = () => {
// Local storage key for storing viewed products
const storageKey = 'viewedProducts';
if (productId) {
// Get existing viewed products from local storage
let viewedProducts = [];
const storedValue = localStorage.getItem(storageKey);
if (storedValue) {
try {
viewedProducts = JSON.parse(storedValue);
} catch (e) {
console.error('Error parsing viewed products from local storage:', e);
viewedProducts = [];
}
}
// Check if product is already in the list
const productExists = viewedProducts.some(product => product.id === productId);
if (!productExists) {
// Add new product to the list
const productData = {
id: productId,
title: productTitle,
handle: productHandle,
viewedAt: new Date().toISOString()
};
viewedProducts.push(productData);
// Update local storage with new list
localStorage.setItem(storageKey, JSON.stringify(viewedProducts));
}
}
// Log all viewed products for debugging
const allViewedValue = localStorage.getItem(storageKey);
if (allViewedValue) {
try {
const allViewedProducts = JSON.parse(allViewedValue);
// Update cart attribute with recently viewed products and market ID
const productIds = allViewedProducts.map(product => product.id).join(',');
const cartAttributes = { '__upsell_recently_viewed_products': productIds};
// Add market ID to cart attributes if it exists
if (marketId) {cartAttributes['__upsell_market_id'] = marketId }
if (productIds || marketId) {
fetch(window.Shopify.routes.root + 'cart/update.js', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
attributes: cartAttributes
})
})
.then(response => response.json())
.catch(error => {
console.error('Error updating cart attributes:', error);
});
}
} catch (e) {
console.error('Error logging all viewed products from local storage:', e);
}
}
};
// Initialize product tracking
trackViewedProducts();
// Add event listener for page changes if using AJAX navigation
window.addEventListener('popstate', trackViewedProducts);
}
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment