Reputation: 51
could someone help me with this problem.
There is requirement to open all links when they are on external domains in _blank. But links in same domain must be opened in same window. I having issue, because I working in 2 domains one is https://www and other just http:// without www, how to open link in same windows on link without www?
function externalLinks() {
var h = window.location.host;
jQuery("a[href^='http']").not("[href*='" + h + "']").not(".forceSameWindow").attr('target', '_blank');
}
now all links exept https://www.something.com opening in blank example: http://something.com
I must do this in jquery/js. I done this by doing hardcoded domain, but what do do nicely!
Thanks for your help!
Upvotes: 0
Views: 2487
Reputation: 897
This is based off your original post
$("a").each(function($a){
$a=$(this);
if(!~this.href.indexOf(document.location.host)||!$a.hasClass('forceSameWindow')){
$a.attr('target','_blank');
}
})
Assuming all links are not set up to _blank
initially
Upvotes: 0
Reputation: 26183
Just change
var h = window.location.host;
to
var h = window.location.host.replace(/^www/,'');
that way it doesn't matter if you are on the www
host or not
Upvotes: 2
Reputation: 4134
var externalLinks = function(){
var anchors = document.getElementsByTagName('a');
var length = anchors.length;
for(var i=0; i<length;i++){
var href = anchor[i].href;
if(href.indexOf('http://h4kr.com/') || href.indexOf('http://www.h4kr.com/')){
return;
}
else{
anchor[i].target='_blank';
}
}
};
This should work :)
Upvotes: 0
Reputation: 2493
You have to force apache to add www.
Add this to your .htaccess
file:
RewriteEngine on
RewriteCond %{HTTP_HOST} !^www.your_domain.com$
RewriteRule ^(.*)$ http://www.your_domain.com/$1 [R=301]
Upvotes: 0