Skip to content

Instantly share code, notes, and snippets.

@inogo
Created April 22, 2016 17:18
Show Gist options
  • Save inogo/52c8178ca7e6de0403466024789bf1bd to your computer and use it in GitHub Desktop.
Save inogo/52c8178ca7e6de0403466024789bf1bd to your computer and use it in GitHub Desktop.
/*
* Yandex.Metrika ecommerce helper script
* Docs: https://yandex.ru/support/metrika/data/e-commerce.xml
* Author: isoshin@outlook.com
*/
window.dataLayer = window.dataLayer || [];
function ecommDetail(products) {
products = [].concat(products);
if (products.length) {
window.dataLayer.push({
"ecommerce": {
"detail": {
"products": products
}
}
});
}
}
function ecommAdd(products) {
products = [].concat(products);
if (products.length) {
window.dataLayer.push({
"ecommerce": {
"add": {
"products": products
}
}
});
}
}
function ecommRemove(products) {
products = [].concat(products);
if (products.length) {
window.dataLayer.push({
"ecommerce": {
"remove": {
"products": products
}
}
});
}
}
function ecommPurchase(order, products) {
products = [].concat(products);
if (products.length) {
window.dataLayer.push({
"ecommerce": {
"purchase": {
"actionField": order,
"products": products
}
}
});
}
}
(function($) {
var callbacks = {
'toCartCallback': function(form) {
var $f = $(form);
ecommAdd({
'name': $f.find('input[name=shk-name]').val(),
'id': $f.find('input[name=shk-id]').val(),
'category': $f.find('input[name=shk-category]').val(),
'price': $f.find('input[name=shk-price]').val(),
'quantity': $f.find('input[name=shk-count]').val()
});
return true;
}
};
$(window).on('load', function() {
// handle details
var products = [];
$('[itemscope][itemtype="http://schema.org/Product"][data-ecomm-collect]').each(function() {
var $t = $(this);
products.push({
'name': $.trim($t.find('[itemprop=name]').text()),
'id': $t.find('[itemprop=productID]').attr('content'),
'category': $t.find('[itemprop=category]').attr('content'),
'price': $t.find('[itemprop=offers] [itemprop=price]').text()
});
});
ecommDetail(products);
// set callbacks
if (typeof SHKtoCartCallback == 'undefined')
window.SHKtoCartCallback = callbacks.toCartCallback;
// handle purchase
if (typeof ecommOrderData != 'undefined') {
ecommPurchase({'id': ecommOrderData.order_id, 'revenue': ecommOrderData.revenue}, ecommOrderData.products);
}
// remove item
$('#shopCart .shk-del').on('click', function() {
var row = $(this).closest('tr[rel=productItem]');
ecommRemove({
'id': row.find('input[rel=productItemId]').val(),
'name': row.find('.prod-title [rel=productItemName]').text()
});
});
});
})(jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment