Last active
August 29, 2015 14:03
-
-
Save erpe/7bc15d9216cc4df0dc05 to your computer and use it in GitHub Desktop.
CoffeeScript GoogleAnalytics analytics.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class @GoogleAnalytics | |
@load: -> | |
((i, s, o, g, r, a, m) -> | |
i["GoogleAnalyticsObject"] = r | |
i[r] = i[r] or -> | |
(i[r].q = i[r].q or []).push arguments | |
i[r].l = 1 * new Date() | |
a = s.createElement(o) | |
m = s.getElementsByTagName(o)[0] | |
a.async = 1 | |
a.src = g | |
m.parentNode.insertBefore a, m | |
) window, document, "script", "//www.google-analytics.com/analytics.js", "ga" | |
if typeof ga isnt 'undefined' | |
ga('create', GoogleAnalytics.analyticsId(), 'auto') | |
ga('send', 'pageview') | |
ga('require', 'displayfeatures') | |
ga('require', 'ecommerce', 'ecommerce.js') | |
# If Turbolinks is supported, set up a callback to track pageviews on page:change. | |
# If it isn't supported, just track the pageview now. | |
if typeof Turbolinks isnt 'undefined' and Turbolinks.supported | |
document.addEventListener "page:change", (-> | |
GoogleAnalytics.trackPageview() | |
), true | |
else | |
GoogleAnalytics.trackPageview() | |
@trackPageview: (url) -> | |
if typeof ga is undefined | |
conole.log("missing ga in item") | |
unless GoogleAnalytics.isLocalRequest() | |
if url | |
ga('send','pageview', url) | |
else | |
ga('set', 'location', location.href.split('#')[0]) | |
ga('send','pageview') | |
@addEcommerceItem: (sku, category, name, price) -> | |
if typeof ga is undefined | |
conole.log("missing ga in item") | |
unless GoogleAnalytics.isLocalRequest() | |
ga('ecommerce:addItem', { | |
'id': parseFloat(Math.random()), | |
'name': name, | |
'sku': sku, | |
'category': category, | |
'price': price, | |
'quantity': '1' | |
}) | |
@trackEcommerceTransaction: (order_id, revenue) -> | |
if typeof ga is undefined | |
conole.log("missing ga in transaction") | |
unless GoogleAnalytics.isLocalRequest() | |
ga('ecommerce:addTransaction', { | |
'id': order_id, | |
'revenue': revenue, | |
}) | |
@trackEcommerce: -> | |
unless GoogleAnalytics.isLocalRequest() | |
ga('ecommerce:send') | |
@isLocalRequest: -> | |
if GoogleAnalytics.documentDomainIncludes "localhost" | |
return true | |
if GoogleAnalytics.documentDomainIncludes('127.0.0.1') | |
return true | |
if GoogleAnalytics.documentDomainIncludes('staging') | |
return true | |
@documentDomainIncludes: (str) -> | |
document.domain.indexOf(str) isnt -1 | |
@analyticsId: -> | |
'UA-XXXX-X' | |
GoogleAnalytics.load() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment