angulartics / angulartics-google-analytics

Google Analytics plugin for Angulartics
MIT License
133 stars 86 forks source link

Fix Universal Analytics detection for async tracking snippets #91

Closed colekettler closed 7 years ago

colekettler commented 7 years ago

Fixes Universal Analytics detection when the alternate async snippet is used, which does not set window.GoogleAnalyticsObject. If window.GoogleAnalyticsObject is undefined, it will default toga.

The analytics.js script defaults the namespace to ga, and renaming the namespace for the async snippet requires setting window.GoogleAnalyticsObject. I think this should cover the standard snippet, async snippets that keep the default namespace, and async snippets that change the namespace.

DanWilkerson commented 7 years ago

Hm. I'm not a huge fan of this, as it breaks support for folks who change the name of the GA global to something different.

colekettler commented 7 years ago

@DanWilkerson Hey, thanks for checking this PR out. We're really appreciative of this plugin, and Angulartics as a whole. 😄

I think that anybody who changed the name of the global will be okay as long as they followed this procedure. I don't think there's any way around setting window.GoogleAnalyticsObject, but I could be wrong. Are there any other cases I should cover?

DanWilkerson commented 7 years ago

That's the problem - the only way for a third party to reliably detect a non-standard global name for Universal Analytics is by using the value stored in window.GoogleAnalyticsObject. I'm leaning towards the solution for this instead being adding a note in our readme to further adjust the async snippet to set GoogleAnalyticsObject, too.

colekettler commented 7 years ago

@DanWilkerson I agree, adding a note to the readme is a good solution. Setting window.GoogleAnalyticsObject to ga in the async snippet has worked well for us thus far.

I'll close this PR out and open one up to update the readme shortly. Thanks for taking the time to review, we've been having a smooth experience with Angulartics and this plugin. 🙌

DanWilkerson commented 7 years ago

Thank you!

fnagel commented 6 years ago

I've had a hard time getting this to work with the async code. This worked for me:

<script>
    window.GoogleAnalyticsObject = 'ga';
    window.ga=window.ga||function(){(ga.q=ga.q||[]).push(arguments)};ga.l=+new Date;

    ga('create', 'MY_CODE', 'auto');
    // ga('send', 'pageview');
</script>
<script async src='https://www.google-analytics.com/analytics.js'></script>

Is there already a way to make things work with the (brand new?) gtag.js code?