Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I set a Page Title with Google Analytics?

The site that I'm working on has really crappy title structure and can't be changed for a variety of reasons. Can I "set" the page title for Google Analytics via JS somehow?

like image 357
Shamoon Avatar asked Sep 06 '11 15:09

Shamoon


2 Answers

The New Way

There's a (currently undocumented feature) that allows you to override the current page's title:

_gaq.push(["_set", "title", "Your Brand New Page Title"]);
_gaq.push(["_trackPageview"]); //will send with the overridden page title

The Old Way

Google Analytics gets the title information from document.title, so you could just set document.title before Google Analytics runs to whatever value you want it to be.

_gaq.push(function(){
    var oldtitle = document.title; 
    document.title = "More Descriptive Title";
    _gaq.push(["_trackPageview"]);
    document.title = oldtitle;
});

Tests in Chrome seem to indicate that this doesn't cause a title flicker, but your results may vary.

like image 135
Yahel Avatar answered Sep 20 '22 23:09

Yahel


This is different in analytics.js (Universal Analytics).

Find details on Google's developer site.

Here are Snippets from the Site:

To send a pageview, you pass the ga function a send command with the pageview hit type:

ga('send', 'pageview');

When this command is executed, the analytics.js library sets the title value using the document.title browser property.

Overriding Default Values

If you need to override the default location information, you should update the title and page values directly.

To override the default page value, you can pass the ga command an additional parameter:

ga('send', 'pageview', '/my-overridden-page?id=1');

Alternatively, to override these values, the send command accepts an optional field object as the last parameter. The field object is a standard JavaScript object, but defines specific field names and values accepted by analytics.js.

    ga('send', 'pageview', {
  'page': '/my-overridden-page?id=1',
  'title': 'my overridden page'
});
like image 23
Dave Avatar answered Sep 22 '22 23:09

Dave