jQuery New window opens external link

  • 2021-07-04 18:07:15
  • OfStack

For external links, in order to keep users in this site, we usually use a new window to open, you can set target= "_ blank". However, manual one is troublesome, and the other one may be missed. This paper queries the key-clicked links through jQuery, and adds relevant attributes to open a new window.


$(document).on('click','a',function(){
var url = this.href,hash='';
if(url.indexOf('#')>-1){
hash = !!url.split('#')[1] ? '#' + url.split('#')[1] :'';
url = url.split('#')[0]; 
}
if(url && url.substr(0,4) == 'http' && url.indexOf('caibaojian.com')<0 ) {
this.href = url.indexOf('?') > -1 ? url+'&utm_source=caibaojian.com'+hash:url+'?utm_source=caibaojian.com'+hash;
this.setAttribute('target', '_blank');
}
})

Related articles: