How-to: Add Google Analytics to App

Stevan,

Thanks for your comment.  For some reason it took about 3 days instead of the quoted 24 hours.

Thanks again,
Daren

Hi.

it should be working.

Thanks to both of you for posting this!!!

I took Stevan's code, pasted it towards to the top of  my Javascript, and replaced it with my Google Analytics ID.  Is there anything else I need to do?

If I just visit the site myself, is that enough to show up on the analytics?  (I don't see anything yet)

Thanks again,

Daren Tolz

Nice! Thanks :D

Hi Ben.

A little turnaround in order to prevent the script from being inserted on each page render : 

  

$(document).on('knack-scene-render.any', function(event, scene) {

var pagetitle = $(’.kn-crumbtrail a:first-child’).text()+’ - ‘+$(’.kn-scene h1’).text();
var pageurl = window.location;
var ga = “<script>\n\n(function(i,s,o,g,r,a,m){i[‘GoogleAnalyticsObject’]=r;i[r]=i[r]||function(){\n(i[r].q=i[r].q||).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),\nm=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)\n})(window,document,‘script’,’//www.google-analytics.com/analytics.js’,‘ga’);\n\nga('create’, ‘UA-xxxxxxxx-x’, ‘auto’);\nga(‘send’, ‘pageview’, {\n ‘page’:’”+pageurl+"’,\n’title’:’"+pagetitle+"’\n});\n\n</script>"

$(ga).remove();
$("#knack-body").append(ga);

});

  

Glad I could share Stevan. I thought I would mention that the title you set for the page is really going to depend on your application and how it is designed. There isn't a super consistent place to grab it no matter what level you are at, etc.. - and sometimes titles show up automatically and sometimes you have to add them. Anyhow, it's possible -- you will just need to evaluate your own application to see where to pull the title from.  The reason this is necessary is because Knack doesn't change the actual TITLE attribute once the app initially loads, and that is what Google analytics uses by default.

Good luck!

Thanks a lot for this.