Resorath
Resorath

Reputation: 1692

Load Google Analytics from tampermonkey

I'm trying to place Google Analytics code inside a Tampermonkey userscript, however the code simply doesn't work as evidenced by:

Here is the script, nice and simple (some values obfuscated):

// ==UserScript==
// @name       GA Injector  
// @namespace  mynamespace
// @version    0.1
// @description  Injects google analytic code for testing
// @match      mywebpage
// @copyright  2014 me
// @require http://code.jquery.com/jquery-latest.js
// ==/UserScript==


Console.log('This part works okay');

(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
    (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
        m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
                        })(window,document,'script','//www.google-analytics.com/analytics.js','ga');

ga('create', 'mytrackingcodeishere', 'auto');
ga('send', 'pageview', {
    'hitCallback': function() {
        console.log('Tracking worked okay!');
    }
});

The script works fine when run in Chrome's javascript console, what is it about Tampermonkey or my configuration that prevents Google Analytics from being run?

Upvotes: 1

Views: 874

Answers (1)

AlexTR
AlexTR

Reputation: 812

Try simply injecting this entire code into the page scope, like this:

var script = document.createElement('script');
script.innerHTML = "..Your JS Code..";
document.body.appendChild(script);

If it does works when run from console, it will this way.

Upvotes: 0

Related Questions