Skip to Content

Stylegala Forums » Forums list » Problem solving

Adding an exception

Adding an exception

post new topic Post new topic    Reply to topic Reply to topic

Author Message
Nimbuz

Junior member
  • Joined: 28 Oct 2007
  • Posts: 56
  • Status: Offline
Reply with quote Post Posted: Sat May 10, 2008 09:41
Hi,

I'm using the following script to open all external links in new window:

function externalLinks() {
if (!document.getElementsByTagName) return;
var anchors = document.getElementsByTagName("a");
for (var i=anchors.length-1; i>=0; i--) {
var anchor = anchors[i];
if (anchor.href && anchor.href.substr(0,7) == "http://")
anchor.target = "_blank";
}
}
window.onload = externalLinks;


but I want to add an exception, like open http://google.com and http://www.google.com in same window.

Thanks

View user's profile Send private message
 
Sponsor
 
Bill Posters

Site Moderator
Reply with quote Post Posted: Sat May 10, 2008 12:44
function externalLinks() {

   if (!document.getElementsByTagName) return;

   var aEls = document.getElementsByTagName('a');
   for (var i = 0, aEl; aEl = aEls[i]; i++) {
      if (aEl.href && aEl.href.indexOf(window.location.hostname) == -1) && aEl.href.indexOf('google.com') == -1) {
         aEl.target = "_blank";
      }
   }

}

window.onload = externalLinks;


In my tests, I've found that comparing the href to window.location.hostname property provides a more reliable means of addressing external links (when using standard, W3C DOM scripting).
Some browsers invisibly prepend the http:// to absolute, internal links (made absolute by using the root slash). This means that looking for the http:// string in the href will sometimes return false positives.

Fwiw, here's my own fairly exhaustive efforts (from a while back) on the issue of targeting new windows for external links.

Flag & toggle external links
_________________
aka 'clemi'

View user's profile Send private message
 

Page 1 of 1

post new topic Post new topic    Reply to topic Reply to topic

Display posts from previous:   

Powered by phpBB. © 2001, 2006 phpBB Group & Logo Design