问题
I am trying to populate the GA e-commerce code using jQuery, or JS. I don't have access to the code, so I am unable to populate them from the actual page - which is a pain in the backside, i know!
I have so far been able to get the order number and order total. To get each product in the basket I have been trying to get each row order-item
and then grab the data to populate an instance of ecommerce:addItem
per item. I then need to append it to the page so i have a ga('ecommerce:addItem', { });
per item in the order.
I was wondering if anyone else has a better idea to do this. Here is my code so far, any improvements would be much appreciated. I think a better option maybe to create the ga('ecommerce:addItem', { });
and then return them to the page, but i am not sure how to do this.
<script>
var order_id = document.getElementsByClassName('order_id')[0].innerText
var order_total = document.getElementsByClassName('order_total')[0].innerText
ga('ecommerce:addTransaction', {
'id': order_id,
'affiliation': 'Test Store',
'revenue': order_total,
'currency': 'GBP'
});
$('.order_item').each(function(){
ga('ecommerce:addItem', {
'id': order_id,
'name': $(this).find('.product-name')[0].innerText,
'sku': $(this).find('.product-sku')[0].innerText,
'price': $(this).find('.item_price')[0].innerText,
'quantity': $(this).find('.iitem_qty')[0].innerText
});
ga('ecommerce:send');
});
ga('ecommerce:clear');
</script>
回答1:
Moving the send function into the each loop worked.
The reason it didn't work was due to the transaction items not being sent to GA
来源:https://stackoverflow.com/questions/41618266/create-the-ga-ecommerce-additem-code-using-js