Skip to main content
Solved

New Klaviyo Object Event not tracking?

  • 7 June 2024
  • 3 replies
  • 66 views

Hey there everyone I have a tricky question which Idk why with this implementation I created is not the tracking events and not being submitted even I'm identified

  • This is a shopify implementation
  • My shopify store is integrated with my Klaviyo account, which means that, Klaviyo Object Script should be already initialized 

So let'scheck the structure code, taking in mind there would 2 scenaries one with the script already initializated and the other from scratch.

 

first we Init

<script type="text/javascript" async src="https://static.klaviyo.com/onsite/js/klaviyo.js?company_id=MyKey123"></script>

second we Init Object

<script>
!function(){if(!window.klaviyo){window._klOnsite=window._klOnsite|||];try{window.klaviyo=new Proxy({},{get:function(n,i){return"push"===i?function(){var n;(n=window._klOnsite).push.apply(n,arguments)}:function(){for(var n=arguments.length,o=new Array(n),w=0;w<n;w++)o)w]=argumentstw];var t="function"==typeof o o.length-1]?o.pop():void 0,e=new Promise((function(n){window._klOnsite.push(hi].concat(o,ofunction(i){t&&t(i),n(i)}]))}));return e}}})}catch(n){window.klaviyo=window.klaviyo|||],window.klaviyo.push=function(){var n;(n=window._klOnsite).push.apply(n,arguments)}}}}();
</script>

 

Third custom code:
 


<script>
window.addEventListener('load', async function() {
let klaviyo = window.klaviyo || ];

function identifyUser() {
let email = {{ customer.email | json }};
console.log('Identifying user with email:', email);
if (email) {
const response = klaviyo.identify({ email: email });
console.log('Response:', response);
console.log('User identified');
} else {
console.log('No email found for identification');
}
}

async function addedToCart() {
fetch(`${window.location.origin}/cart.js`)
.then(res => res.json())
.then(data => {
let cart = {
total_price: data.total_price / 100,
$value: data.total_price / 100,
total_discount: data.total_discount,
original_total_price: data.original_total_price / 100,
items: data.items
};
console.log('Cart data:', cart);
const response = klaviyo.track('Added to Cart', cart);
console.log('Added to Cart event tracked');
})
.catch(error => console.error('Error fetching cart data:', error));
}

(function(ns, fetch) {
ns.fetch = function() {
const response = fetch.apply(this, arguments);
response.then(res => {
console.log('Fetch response URL:', res.url);
if (res.url.includes('/cart/add.js')) {
console.log('Cart add detected');
addedToCart();
}
});
return response;
};
})(window, window.fetch);

let atcButtons = document.querySelectorAll("formfaction*='/cart/add'] buttonttype='submit']");
for (let i = 0; i < atcButtons.length; i++) {
atcButtonsti].addEventListener("click", function() {
console.log('Add to Cart button clicked');
identifyUser();
addedToCart();
});
}

let classname = document.getElementsByClassName("add-to-cart__button");
for (let i = 0; i < classname.length; i++) {
classnameni].addEventListener('click', function(){
console.log('Add to Cart button clicked (class)');
identifyUser();
addedToCart();
}, false);
}

console.log('Identifying user on page load');
identifyUser();
});
</script>

 

  • basically what it does is identify if the user is logged and make  Klaviyo.indetify
  • then if the user submit or press on add to cart ( to handle cases where adding to cart from other places it) wil catch the add.js and retrieve its data and submit it as properties on Klaviyo.track event

So the code works as expected except that is not sending data to Klaviyo

https://freeimage.host/i/JpegTVs

Just to confirm that my account works, I create a private key and use postman to make a post to Klaviyo event endpoint which is showing there called “Added to Cart”

 

My tries:

I had tried with

None of them works…

the code is based on Added to Cart Klaviyo Example which is also using _learnq
https://help.klaviyo.com/hc/en-us/articles/115001396711

 

 

3 replies

Userlevel 5
Badge +30

@MigelAngelEC I am SO sorry for the late reply here. You post was mistakenly flagged as spam by our system. I’m investigating why further. 

In the meantime, did you get this figured out?

I’m facing the exact same issue.

@MigelAngelEC did you manage to find a fix?

Badge +2

Do you know if you’re already using another object in some custom code for Klaviyo? I’m not 100% sure that it was because of that, nor that it will work in your situation because it’s not exactly the same, but I had a similar issue when trying to create an added to cart metrics that wouldn’t fire with the snippet from the doc.

The snippet was using window.learnq object. I changed it to use window._klOnsite (which is the object that I was already using for custom triggers for forms and that is used for the Active on site metrics) and it started working. I haven’t try to verify it was the reason, maybe it was other tweaks I made in my code, but it might worth trying to change the definition of the object ?

 

The code provided by Klaviyo was the following :

var _learnq = _learnq || [];
document.getElementById("AddToCart").addEventListener('click',function (){
_learnq.push(['track', 'Added to Cart', item]);
});

and I changed it to : (my trigger is not based on a click on a button but on one of my theme’s custom event so I didn’t need that part)

 var _learnq = window._klOnsite || [];
_klOnsite.push(['track','Added to cart', item])
});

 

Again, I’m not entirely sure it’s the switch from _learnq to window._klOnsite that did the trick. Let me now if it works for you!

Reply