简体   繁体   中英

Google Analytics Event Tracking using javascript

Is there an alternative to using the google analytics onclick event?

 onclick="_gaq.push(['_trackEvent', 'category', 'action', 'opt_label', opt_value]);"> 

I have a website that has a large amount of links that I want to track. However, I don't want to have to go and add this to every link I have. I have done some research but cant seem to find something that work better. Any suggestions?

You could get all anchors and attach an onclick event that will call the tracker function. Something like this:

  var links = document.getElementsByTagName('a');
  for (var i = 0; i < links.length; ++i) {
    links[i].addEventListener('click', fireAnalyticsEvent, false);
  }
  function fireAnalyticsEvent(ev) {
   _gaq.push(['_trackEvent', 'category', 'action', 'opt_label', ev.srcElement.getAttribute('href')]);
  }

However, bear in mind that as far as outgoing links that are opened at the same tab are concerned, GA is not reliable: the request to analytics might be cut off when the page navigates to the new URL. If this is what you are trying to track then you would have to use a server-side redirect system to track the clicks (something like a python/php/your fave server language that will get the URL as a parameter, perform the tracking logic, and then return 302 redirect headers to have the client navigate to the URL that it got as input).

You could alternativley solve your problem by making a php "kicker/redirect"-page that will take a url parameter and if you add standard GA to that page, it will track the parameter right there.. You can ofcourse use javascript and get the query parameter and track as "event" if you want.

Edit: So you'd need to rewrite your links, OR use jquery to manipulate the url at runtime: http://techpad.co.uk/content.php?sid=103

--

I think it would be cleaner than.. (abstract) somehow catching all click events, then filter if the links is in a certain element, or links to certain destination.. doable, but too messy in my opinion.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM