Google analytic in Javascript


Google analytic class for e-commerce checkout

module.exports = function Analytics(currency, send_to, properties) {
    this.currency = currency;
    this.send_to = send_to;
    this.properties = properties;
    this.pageMeasurement = {
        startTime: 0,
        endTime: 0
    };
    window.dataLayer = window.dataLayer || [];
    this.gtag = function () { dataLayer && dataLayer.push(arguments); }





    this.init = function () {
        this.gtag('js', new Date());
        // Set global currency
        this.gtag('set', {
            'currency': this.currency,
            'send_to': this.send_to
        });



        var that = this;
        this.properties.forEach(function (prop) {
            if (!prop.trackingId) {
                that.error("Invalid tracking id : " + prop && prop.config && prop.config.groups);
                return;
            }

            that.gtag('config',       prop.trackingId,  
                                       Object.assign({}, prop.config));
        });
    }


Page load event


    this.pageLoad = function (page) {
        if (!this.properties || !this.properties.length) {
            return;
        }

        if (!page || !page.path) {

            this.error("Invalid page : " + page && page.path);

            return;

        }

        var that = this;
        this.measureTimeStart(this.pageMeasurement);
        this.properties.forEach(function (prop) {
            if (!prop.trackingId) {
                that.error("Invalid tracking id : " + prop && prop.config && prop.config.groups);
                return;
            }

            that.gtag('config',
                prop.trackingId,
                Object.assign({}, prop.config, {
                    page_path: page.path + ((prop.config && prop.config.groups && prop.config.groups === 'company') ? location.search : ''),
                    page_title: page.title,
                    'send_page_view': true
                }));
        });
    }



    this.measureTimeStart = function (measurement) {
        // Feature detects Navigation Timing API support.
        if (window && window.performance && measurement) {
            // Gets the number of milliseconds since page load
            measurement.startTime = performance.now();
        }
    }

    this.pageLoadOnCompleted = function (pageName) {

        // Feature detects Navigation Timing API support.
        if (window && window.performance) {
            // Gets the number of milliseconds since page load
            // (and rounds the result since the value must be an integer).
            var timeSincePageLoad = Math.round(performance.now() - this.pageMeasurement.startTime);
            this.gtag('event', 'timing_complete', {
                'name': 'page load time',
                'value': timeSincePageLoad,
                'event_category': 'page load',
                'event_label': pageName,
                'send_to': 'company'

            });

        }

    }







Pick up product item event







    this.createItem = function (merchantName, price, quantity, position, deliveryMethod) {

        if (!merchantName || (!price && price !== 0) || !quantity || isNaN(price) || isNaN(quantity)) {

            this.error("Invalid create item : { merchant: " + merchantName + ", price: " + price + ", quantity: " + quantity + ", pos: " + position + " }");

            return;

        }

        return {

            "id": merchantName + '_' + quantity + '_' + price + '_' + position,

            "name": merchantName + '_' + quantity + '_' + price + '_' + position,

            "list_position": position,

            "quantity": quantity,

            "price": parseFloat(price),

            "category": 'eGift Card',

            'delivery_method': deliveryMethod

        };

    }



    this.onClickTab = function(name, category) {

      this.gtag('event', 'click_tab', {

        'event_label': name,

        'event_category': category,

        'event_page': location.pathname + location.search

      });

    }







    this.onClickButton = function(name, category) {

      this.gtag('event', 'click_button', {

        'event_label': name,

        'event_category': category,

        'event_page': location.pathname + location.search

      });

    }





Add to cart event




    this.addToCart = function (item) {

        if (!item || !item.id || !item.quantity || !item.price) {

            this.error("Invalid add to cart : " + item);

            return;

        }

        this.gtag('event', 'add_to_cart', {

            "items": [item]

        });

    }



    this.removeFromCart = function (item) {

        if (!item || !item.id || !item.quantity || !item.price) {

            this.error("Invalid remove from cart : " + item);

            return;

        }

        this.gtag('event', 'remove_from_cart', {

            "items": [item]

        });

    }


Check out Event


    this.beginCheckout = function (items) {        if (!items || !items.length) {            this.error("Invalid checkout begin : " + items);            return;        }        this.gtag('event', 'begin_checkout', {            "items": items        });    }

    this.checkoutProgress = function (items) {

        if (!items || !items.length) {

            this.error("Invalid checkout progress : " + items);

            return;

        }

        this.gtag('event', 'checkout_progress', {

            "items": items

        });

    }



Setup Purchase Event


    this.purchase = function (merchantId, orderNumber, totalAmount, totalTax, items) {

        if (!items || !items.length || !totalAmount || !merchantId || !orderNumber) {

            this.error("Invalid purchase : { totalAmount: " + totalAmount + ", merchantId: " + merchantId, ", totalTax: " + totalTax + " }");

            return;

        }

        var that = this;

        this.gtag('event', 'purchase', {

            "transaction_id": orderNumber,

            "affiliation": merchantId,

            "value": totalAmount,

            "currency": that.currency,

            "tax": totalTax,

            "items": items

        });

    }


Catch Up Error


    this.error = function (err, fatal) {
        if (!err) { return; }
        try {
            this.gtag('event', 'exception', {
                'description': err,
                'fatal': !(!fatal),
                'send_to': 'company'
            });

        } catch (err) {

 }

    }

}

Comments

Popular Posts