jjNford
jjNford

Reputation: 5270

Google Analytics with no HTML page

How can I run a Google Analytic's snippet from a .js file that contains no HTML? With no HTML present I receive the console error:

Uncaught TypeError: Cannot read property 'parentNode' of undefined

CLARIFICATION Sorry this was a very unclear question. I had created a Chrome Extension that does not have an actual page but rather injects a script to be run on a declared webpage. I wanted Google Analytic's to keep count of how many time the script was used. My Solution is provided below.

Upvotes: 2

Views: 1499

Answers (2)

jjNford
jjNford

Reputation: 5270

The problem is there is no page element because the script is being injected.

Here is the fix:

window.onload = function() {

    var head = document.getElementsByTagName("head")[0];

    var code = document.createElement('script');
    code.text = "var _gaq = _gaq || [];\n_gaq.push(['_setAccount', 'UA-XXXXXXXX-X']);\n_gaq.push(['_trackPageview']);";

    var ga = document.createElement('script');
    ga.type = 'text/javascript';
    ga.async = true;
    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';

    var s = document.getElementsByTagName('script')[0];

    head.appendChild(code);
    code.parentNode.insertBefore(ga, s);
};

Upvotes: 3

Andrew Odri
Andrew Odri

Reputation: 9450

I assume you want to register page views on Google Analytics when you do not have control over the HTML...

If so, this little piece of documentation provides quiet a bit of information on this: http://code.google.com/apis/analytics/docs/tracking/asyncUsageGuide.html

This is what allows the remote script to be loaded and functions called:

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

And this is the function that tells analytics what to track:

_gaq.push(...);

This will create an async script element, which will load load all the analytics code. Anything that gets pushed onto the _gaq array will get processed by analytics. From there, it's up to you to determine what to push onto that array. Maybe this will help you: http://code.google.com/apis/analytics/docs/gaJS/gaJSApi_gaq.html

Upvotes: 0

Related Questions