CJD
CJD

Reputation: 747

How does Google Analytics In-Page Analytics work?

Google Analytics features an 'In-Page Analytics' view to show click-through rates and other information directly on your own website. I'm looking to build something similar that logs all clicks.

The problem is I'm not really sure how Google implement their In-Page Analytics views - they seem to use an iframe, or two, and have injected their own HTML and JavaScript onto other pages.

How would one go about doing such a thing - are iframes the best way to go? How would you avoid the same-origin security policies of Javascript if domainX is trying to manipulate the rendering of domainY?

Upvotes: 6

Views: 6286

Answers (2)

Timo
Timo

Reputation: 693

This is a very interesting question. You're right, the same origin policy forbids injecting JS. But Google Analytics has an advantage: it already is in your site (the tracker code).

So here is how it works (as far as I can see):

  • When you open in-page analytics, you are first taken to https://www.google.com/analytics/reporting/iyp_launch
  • This page redirects to your site and adds a Google session to the url (like http://example.com/#gaso=THESESSION
  • The tracker now checks if the referrer is iyp_launch and gaso is set. If yes, it does not only load the tracker, but also injects the JS needed for requesting further data and rendering the overlays. This way, the JS is executed inside the frame (or window) and bypasses the same-origin policy.
  • Since Google Anaytics already tracks your visit (i.e. identifies you as the same user that viewed the previous page), it can from then on inject the additional JS along with the tracker until your visit is over (i.e. you close the page). This way, the overlays can be rendered again after you click a link.

So I guess the bottom line is this: Things like in-page analytics can be done if the site's owner has already trusted you by adding a script you control to his website (this is a good example why one should be very careful before doing such a thing). If you don't have that kind of access to the site, it might be impossible to bypass the same-origin policy - at least, I can't think of another way to do it (except maybe proxying all the requests through your sever, but that leads to other major problems).

Upvotes: 9

Alxandr
Alxandr

Reputation: 12431

I think this can be done quite simply. You inject javascript that makes sure that whenever a user clicks a link it requests/posts to a special page in the iframe. Something like this (jquery):

$('a').live('click', function() {
    $('#' + iframeid).attr('http://somedomain.com/my_magic_page.php?linkClicked=' + $(this).attr('id') + '&page=' + window.location.toString());
}

Don't know if it'll work though.

Upvotes: -1

Related Questions