Google Analytics JS

How do I import Google Analytics js? Can I just require("") it like you would with (for example) moment js?

This is the library: https://developers.google.com/analytics/devguides/collection/analyticsjs/

Please advise. Thanks

That depends on what dependencies that library have. Since that API is meant to be used in a browser it’s a chance it wont work.

Hi, i just tried and do the following

  1. Create a analytics.js like this
var ua = "UA-XXXXX-XX"; //Put here your tracking code

var trackAction = function(event, event_category, event_action, event_label) {
  var url = 'http://www.google-analytics.com/collect';
  var ua_request = "v=1&&tid="+ua+"&cid=555&t="+event+"&ec="+encodeURIComponent(event_category)+"&ea="+encodeURIComponent(event_action)+"&el="+encodeURIComponent(event_label);
  fetch(url, {
          method: 'post', 
          headers: {
              "Content-type": "application/x-www-form-urlencoded; charset=UTF-8"
          },
          body: ua_request
  })
}

module.exports = {
  trackAction: trackAction
}

  1. Add the following section on your unoproject
  "Includes": [
    "**.js:Bundle"
  ]
  1. On any page use this code to track events:
	<JavaScript>
		var analytics = require('/analytics.js');
		analytics.trackAction('event', 'event_category', 'event_action', 'event_label');
	</JavaScript>

And it works! Try on your project :slight_smile:

Regards

John

I forgot to tell, but you can modify that funcion to measure other kind of things. To do it, check the documentation here:

https://developers.google.com/analytics/devguides/collection/protocol/v1/devguide

John

Hey,

Thanks a lot for the help!

Since posting this there has been some basic implementation of native Firebase Analytics, which has many advantages over a js analytics library, you can check that out here