I’m developing a theme extension to save UTM tracking parameters in the Shopify cart. This extension should activate when the page loads and check the URL parameters. If it detects any values for utm_source, these should be appended to the cart attributes, ensuring they persist even if the URL changes after that.
Below is the code I’m currently working with:
{% comment %}
Script designed to gather marketing parameters on shop entry
{% endcomment %}
<script>
const cartContents = {{ cart.attributes }}
if (!cartContents.UTMData) cartContents.UTMData = []
const searchParams = new URLSearchParams(window.location.search);
for (const [key, value] of searchParams.entries()) {
if (key === "utm_source" && !cartContents.UTMData.includes(value)) {
cartContents.UTMData.push(value)
console.log(cartContents, 'updated cart attributes')
}
}
fetch(window.Shopify.routes.root + 'cart/update.js', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
attributes: cartContents
})
})
.then(function(result) {
return result.json();
})
.then(function(output) {
console.log(output);
})
.catch(function(error) {
console.error(error);
});
</script>
{% schema %}
{
"name": "UTMTracking",
"target": "body",
"settings": []
}
{% endschema %}
I’m facing this JavaScript error: Uncaught SyntaxError: Unexpected token '=>'. What might be causing this syntax problem?