UNPKG

@shopgate/tracking-core

Version:

Tracking core library for the Shopgate Connect PWA.

44 lines • 8.64 kB
function _typeof(obj){if(typeof Symbol==="function"&&typeof Symbol.iterator==="symbol"){_typeof=function _typeof(obj){return typeof obj;};}else{_typeof=function _typeof(obj){return obj&&typeof Symbol==="function"&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj;};}return _typeof(obj);}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}function _defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||false;descriptor.configurable=true;if("value"in descriptor)descriptor.writable=true;Object.defineProperty(target,descriptor.key,descriptor);}}function _createClass(Constructor,protoProps,staticProps){if(protoProps)_defineProperties(Constructor.prototype,protoProps);if(staticProps)_defineProperties(Constructor,staticProps);return Constructor;}function _callSuper(_this,derived,args){function isNativeReflectConstruct(){if(typeof Reflect==="undefined"||!Reflect.construct)return false;if(Reflect.construct.sham)return false;if(typeof Proxy==="function")return true;try{return!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}));}catch(e){return false;}}derived=_getPrototypeOf(derived);return _possibleConstructorReturn(_this,isNativeReflectConstruct()?Reflect.construct(derived,args||[],_getPrototypeOf(_this).constructor):derived.apply(_this,args));}function _possibleConstructorReturn(self,call){if(call&&(_typeof(call)==="object"||typeof call==="function")){return call;}return _assertThisInitialized(self);}function _assertThisInitialized(self){if(self===void 0){throw new ReferenceError("this hasn't been initialised - super() hasn't been called");}return self;}function _getPrototypeOf(o){_getPrototypeOf=Object.setPrototypeOf?Object.getPrototypeOf:function _getPrototypeOf(o){return o.__proto__||Object.getPrototypeOf(o);};return _getPrototypeOf(o);}function _inherits(subClass,superClass){if(typeof superClass!=="function"&&superClass!==null){throw new TypeError("Super expression must either be null or a function");}subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,writable:true,configurable:true}});if(superClass)_setPrototypeOf(subClass,superClass);}function _setPrototypeOf(o,p){_setPrototypeOf=Object.setPrototypeOf||function _setPrototypeOf(o,p){o.__proto__=p;return o;};return _setPrototypeOf(o,p);}/* global fbq */import{logger}from'@shopgate/pwa-core/helpers';import BasePlugin from"../Base";/** * Tracking plugin for Facebook */var FbPixel=/*#__PURE__*/function(_BasePlugin){/** * Constructor * * @param {Object} options Common Tracking Configuration * @param {boolean} [options.overrideUnified] If true -> overrides our unified tracking system * @param {boolean} [options.useNativeSdk] If true -> send data via our unified tracking system * to the native sdk * @param {Object} [options.config] Configuration for facebook pixel tracking * @param {Array} [options.config.pixelIds] List of Facebook pixels */function FbPixel(options){var _this2;_classCallCheck(this,FbPixel);var trackerName='facebookPixel';var extendedDefaults={config:{pixelIds:[]}};_this2=_callSuper(this,FbPixel,[trackerName,options,extendedDefaults]);if(_this2.options.useNativeSdk){logger.warn('SgFbPixelTracking: no native SDK support for this plugin');return _possibleConstructorReturn(_this2);}if(!_this2.options.config.pixelIds.length){logger.warn('SgFbPixelTracking: pixels missing');return _possibleConstructorReturn(_this2);}_this2.initPlugin();return _this2;}/** * Initiate and setup the SDK */_inherits(FbPixel,_BasePlugin);return _createClass(FbPixel,[{key:"initPlugin",value:function initPlugin(){var _this3=this;// Load the fb pixel tracking sdk /* eslint-disable eslint-comments/no-unlimited-disable */ /* eslint-disable */!function(f,b,e,v,n,t,s){if(f.fbq)return;n=f.fbq=function(){n.callMethod?n.callMethod.apply(n,arguments):n.queue.push(arguments);};if(!f._fbq)f._fbq=n;n.push=n;n.loaded=!0;n.version='2.0';n.queue=[];t=b.createElement(e);t.async=!0;t.src=v;s=b.getElementsByTagName(e)[0];s.parentNode.insertBefore(t,s);}(window,document,'script','https://connect.facebook.net/en_US/fbevents.js');/* eslint-enable */var pixelsForInit=this.options.config.pixelIds.slice(0);var firstPixel=pixelsForInit.shift();FbPixel.sendToFb(firstPixel.toString(),undefined,'init');/* * Add multiple pixel Ids. * Warning: This is not official supported by facebook, but seems to work */pixelsForInit.forEach(function(pixel){FbPixel.sendToFb(pixel.toString(),undefined,'addPixelId');});/** * The pixel tracking have a PageView und ViewContent Event. The PageView event should be called * on every page. It has no params */FbPixel.sendToFb('PageView');// Register for some events /* eslint-disable camelcase */this.register.completedRegistration(function(data){FbPixel.sendToFb('CompleteRegistration',{content_name:data.registrationMethod});});this.register.viewContent(function(data,rawData){var fbParams={content_type:data.type};if(data.type==='product'&&typeof rawData!=='undefined'){fbParams.content_ids=[data.id];fbParams.content_name=rawData.product.name;fbParams.value=parseFloat(_this3.getPrice(rawData.product.amount));fbParams.currency=rawData.product.amount.currency;}else{fbParams.content_ids=[data.id];fbParams.content_name=data.name;}FbPixel.sendToFb('ViewContent',fbParams);});this.register.addedPaymentInfo(function(){FbPixel.sendToFb('AddPaymentInfo');});this.register.purchase(function(data){var productIds=FbPixel.getProductIds(data.items);var fbParams={content_ids:productIds,content_type:data.type,value:_this3.getPrice(data),currency:data.currency};if(productIds.length===1){fbParams.content_name=data.items[0].name;}FbPixel.sendToFb('Purchase',fbParams);});this.register.initiatedCheckout(function(data,rawData){var productIds=FbPixel.getProductIds(rawData.cart.products);var fbParams={content_ids:productIds,content_type:'product',value:_this3.getPrice(data),currency:data.currency,num_items:data.numItems};if(productIds.length===1){fbParams.content_name=rawData.cart.products[0].name;}FbPixel.sendToFb('InitiateCheckout',fbParams);});this.register.addToCart(function(data){FbPixel.sendToFb('AddToCart',_this3.getParamsForAddToCartAndWishlist(data));});this.register.addToWishlist(function(data){FbPixel.sendToFb('AddToWishlist',_this3.getParamsForAddToCartAndWishlist(data));});this.register.search(function(data,rawData){var productIds=FbPixel.getProductIds(rawData.products);var fbParams={content_ids:productIds,content_type:data.type,search_string:data.query};FbPixel.sendToFb('Search',fbParams);});}/** * Send data to the facebook tracker * @param {string} eventName Name of the event * @param {Object} [params] Params for the event * @param {string} [typeParam] Type of the tracker call * @returns {void} */},{key:"getPrice",value:/** * Returns the correct price net or gross price. Depending on this.options.useNetPrices * * @param {Object} amount Price Object * @returns {number|string} net or gross price */function getPrice(amount){if(this.options.useNetPrices){return amount.priceNet||amount.valueNet||amount.net||amount.revenueNet;}return amount.priceGross||amount.valueGross||amount.gross||amount.revenueGross;}/** * Returns the params for the AddToCart and AddToWishlist events * * @param {Object} data Converted data from the parent plugin * @returns {Object} Params for the fb event */},{key:"getParamsForAddToCartAndWishlist",value:function getParamsForAddToCartAndWishlist(data){var _this4=this;var productIds=FbPixel.getProductIds(data.items);var value=0;var currency='EUR';data.items.forEach(function(item){value+=_this4.getPrice(item);currency=item.currency;// eslint-disable-line prefer-destructuring });var fbParams={content_ids:productIds,content_type:data.type,value:value,currency:currency};if(productIds.length===1){fbParams.content_name=data.items[0].name;}return fbParams;}/* eslint-enable camelcase */}],[{key:"sendToFb",value:function sendToFb(eventName,params,typeParam){var type=typeParam||'track';fbq(type,eventName,params);}/** * Extract the product Ids from an array with products * * @param {Array} products Array with products * @returns {Array} Array of product Ids */},{key:"getProductIds",value:function getProductIds(products){return products.map(function(product){return product.productNumber||product.uid||product.id;});}}]);}(BasePlugin);window.SgFbPixelTracking=FbPixel;export default FbPixel;