Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect if Google Analytics is loaded and able to track custom Events

We're having some issues when we're loading an iframe with a video player that sends playback Events to Google Universal Analytics (analytics.js) loaded inside that iframe (on another domain). The GA tracker is not being loaded on iOS devices and because of that, no event tracking is being sent to GA.

On Android and other devices including desktop it works just fine, but not on iOS unless I changed the third-party cookies setting that comes default on iOS Safari.

I did a test using a cookie-less method for Google Analytics (https://github.com/Foture/cookieless-google-analytics) and that way iOS devices were able to correctly send track Events to GA. However, I want to use that method only as a fallback when the regular GA method don't work, because the UserId that is created via the Fingerprint method is not very unique on mobile devices.

So I need a way to detect when the regular GA method is able to track events and if is not able, either because the tracker was not loaded or cookies are disabled, then use the cookie-less method to load GA and track the events.

Thanks!

like image 205
Guillermo Avatar asked Oct 19 '22 13:10

Guillermo


1 Answers

You should use check JavaScript window.ga && ga.loaded variables before using ga() method to track events:

if(window.ga && ga.loaded) { {
    // if yes, rely on GA to follow link
    ga('send', 'event', 'outbound', 'click', url, {
        'transport': 'beacon',
        'hitCallback': function(){document.location = url;}
    });
} else {
    // if not, follow link ourselves
    document.location = url;
}

Se more on https://hacks.mozilla.org/2016/01/google-analytics-privacy-and-event-tracking/

like image 80
CralDk Avatar answered Nov 01 '22 09:11

CralDk