Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Send Analytics event from background chrome extension

I'm trying to send an event to Google Analytics from background.js (the background script) of my chrome extension.

I put this code in my background.js file

var _gaq = _gaq || [];
_gaq.push(['_setAccount', _AnalyticsCode]);
_gaq.push(['_trackPageview']);

(function() {
  var ga = document.createElement('script');
  ga.type = 'text/javascript';
  ga.async = true;
  ga.src = 'https://ssl.google-analytics.com/ga.js';
  ga.checkProtocolTask = null;
  var s = document.getElementsByTagName('script')[0];
  s.parentNode.insertBefore(ga, s);
})();

and I try to send this event:

 _gaq.push(['_trackEvent', 'event_send', 'event_label');

but Im not seeing the event on Analytics dashboard. I also added to my manifest.json file this line: "content_security_policy": "script-src 'self' https://ssl.google-analytics.com; object-src 'self'", What do I need to do to make it work from the background?

like image 770
Dkova Avatar asked Mar 19 '26 20:03

Dkova


1 Answers

This is the code I use. You do need to set the checkProtocolTask for an extension. Not sure what you are doing with _gaq, but your _gaq.push line is missing a closing bracket. Also, you are using a deprecated version of analytics. See here: https://developers.google.com/analytics/devguides/collection/gajs/gaTrackingOverview

    // Standard Google Universal Analytics code
    // noinspection OverlyComplexFunctionJS
    (function(i, s, o, g, r, a, m) {
        i['GoogleAnalyticsObject'] = r;
        // noinspection CommaExpressionJS
        i[r] = i[r] || function() {
                (i[r].q = i[r].q || []).push(arguments);
            }, i[r].l = 1 * new Date();
        // noinspection CommaExpressionJS
        a = s.createElement(o),
            m = s.getElementsByTagName(o)[0];
        a.async = 1;
        a.src = g;
        m.parentNode.insertBefore(a, m);
    })(window, document, 'script',
        'https://www.google-analytics.com/analytics.js', 'ga');
    ga('create', TRACKING_ID, 'auto');
    // see: http://stackoverflow.com/a/22152353/1958200
    ga('set', 'checkProtocolTask', function() { });
    ga('set', 'appName', 'Photo Screensaver');
    ga('set', 'appId', 'photo-screen-saver');
    ga('set', 'appVersion', '<version here>');
    ga('require', 'displayfeatures');

Also, don't forget to add https://www.google-analytics.com to the"content_security_policy" in your manifest.

like image 50
Michael Updike Avatar answered Mar 21 '26 08:03

Michael Updike



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!