Jump to content

JavaScript to determine target attribute

disco_cowboy's Photo
Posted Apr 30 2012 08:53 AM
1652 Views

I have some Javascript code I am using for Google Analytics purposes to autotrack cross domain activity. This has been working great for me but I recently noticed an issue with links that have a target attribute value of _blank. When these links are clicked my script ends up loading the requested page in the parent window as well as the target window instead of just the target window. So how do I determine when target="_blank" in Javascript so I can make adjustments to my code?

/*Regex list of on-site domains, pipe and backslash delimited. */
var wa_onsiteDomains = /mydomain\.com|my2nddomain\.com|my3rddomain\.com|javascript/i;

//Display-friendly domain and path name
var wa_displayDomain = location.hostname.replace("www.","").toLowerCase();
var wa_displayPathname = location.pathname.toLowerCase();

/*Used to unobtrusivly add events to objects*/
function unobtrusiveAddEvent (element,event,fn) {
   var old = (element[event]) ? element[event] : function () {};
   element[event] = function () {fn(); old();};
}

function wa_crossDomainLink(i) {
	return function () { 
		var thisLink = decodeURI(wa_links[i]);
		if (typeof(_gaq) == "object")
			_gaq.push(['_link', thisLink]); return false;
	};
}

var wa_links = document.links;
if ( wa_links ){
	for(var i=0; i<wa_links.length; i++) {
		if( wa_links[i].href.match(wa_onsiteDomains) && !wa_links[i].href.match(location.hostname)){
		unobtrusiveAddEvent( wa_links[i], 'onclick' , wa_crossDomainLink(i));
		}
	}
}


Thanks!

Tags:
1 Subscribe


1 Reply

0
  Robin Nixon's Photo
Posted Jun 11 2012 12:34 AM

I think this page may have some information. It details a known Google Analytics bug in certgain circumstances when using _blank:

http://drupal.org/node/1057688