Fall Sale! Code FALL2024 takes 25% OFF our Pro Plugins & Books »
Web Dev + WordPress + Security

Targeting External Links Intelligently

In the beginning…

In the time of the dinosaurs, HTML authors controlled the way anchors opened by adding target="_blank" as an attribute on an anchor tag. Then the molten mass of Internet began to cool into the thin crust of Web 2.0, the continents began to separate and there came a great migration of pages from HTML to the shinier, new XHTML. Most authors didn’t know what that meant, but it had an “X” in it, so it must be cool, they thought.

Alas, there came a great despair as the beloved target="_blank" attribute was no longer looked kindly upon by The Great Validator. The new XHTML pages would not wear the Shiny Badge of Validation Love.

[ Young Planet Earth ] Designers, developers and former blink taggers mourned the passing of new windows and slogged on, heads hung low… until March 4th, 2003. On that day, Kevin Yank of SitePoint.com delivered the news that one could use JavaScript to code target="_blank" on all anchors upon which one had set the rel="external" attribute after the pages had loaded. The pages would receive the much sought after blessing of The Great Validator and anchors could open new windows without extensive JavaScripting.

Oh, how the authors rejoiced in the discovery of this new treasure. Then came the Great Usurpers: User Experience Advocates who said, “Thine actions shall bring about the decline of the Great Internet. The choice of _Blank and _Self belongs to the Almighty User.” Once again, a wave of sorrow swept the Internet.

until today.

The New Internet

Website designers and developers have a great many tools at their disposal these days. Like power tools, these things can help or hurt us. In theory, the idea of opening external links in a new window sounds very sane. If everybody used it this idea intelligently, it would be, well, smart.

In fact, I’m surprised my browser doesn’t allow me to specify what to do with links that take me to a different domain. It seems like a reasonable enough expectation.

Moving along, since there’s already scripts out there which set the target attribute to “_blank” and authors who’ve written the tutorials already, so I’ll just get to the point of this script and why it’s different.

Here’s the list of goals and requirements I used in writing this script:

  • Easy – I didn’t want to have to ever touch it again, even to configure it with defaults. I just wanted to include it on the page and be done with it.
  • Easier – I didn’t want to have to set rel="external" on anything. I figured the script should be smart enough to determine if a link is external or interal by comparing the domain of the site with the href of the anchor.
  • Accessible – The user needed to be able to silence it, and at worse, choose the course of action when an external link was encountered.

I used jQuery as the base library, but obviously it could be easily translated to another library or to library independence.

Stay on target… stay on target…

Having stalled long enough, and with no further ado, 40 lines of “anchor targeted window scripting” bliss (with attached line-by-line description):

(function(){
  var extAnchorTarget = function () {
    var msgtxt = null, usropt = null, askopt = null;
    msgtxt = "Click OK to open this link in a new window "
           + "or cancel to open it in this window.";
    usropt = $(":radio:checked[name=extwinopt]").val() || 0;
    usropt = parseInt(usropt);
    switch (usropt) {
      case 2:
        this.target = "_blank";
      break;
      case 1:
        this.target = "_self";
      break;
      case 0:
      default:
        askopt = confirm(msgtxt);
        this.target = !askopt ? "_self" : "_blank";
      break;
    }
    return true;
  };
  var labelAnchors = function () {
    var winhome = document.domain.split(".").reverse();
        winhome = winhome[1]+"."+winhome[0];
    $("a").each(function(i){
      var lnkhome = this.href.split("/")[2].split(".").reverse();
          lnkhome = lnkhome[1]+"."+lnkhome[0];
      if (!winhome.match(lnkhome)) {
        $(this).addClass("external");
        $(this).click(extAnchorTarget);
      } else {
        $(this).addClass("internal");
      }
    });
  };
  $(function(){
    labelAnchors();
  });
})();

If you’re using jQuery on your site already, just load this script and all of your target="_blank"-anchors-opening-in-new-windows dreams will come true.

Ultimately, this script would be integrated with two additional features:

  • Modals – At the moment, this script relies on the browser confirm function which is a bit ugly and klunky. A polished modal window that would appear as needed would make this the real deal.
  • Cookies – Having integrated a lovely modal widget, we should store the user’s preference to prevent our script from bugging them.

You’ll notice that on Line 6, the script is looking for a form value which contains the user options. While it will silently default to asking the user, this would ultimately be the place where we might also check for a cookie value.

The demo (written in shiny XHTML 1.1 Strict) includes a form which works, but which is obviously reset every time the page is loaded. This would be a problem for a website without a cookie solution, though it’s less apparent in the single page demo.

This script now has the potential to fill the requirements outlined above. It performs its own domain to href comparison, so I could throw it right into an application. I don’t have to set additional values on any attributes, though there’s probably some good reason I should be adding rel="external" to off-site links anyway. It contains a built-in mechanism for asking the user, rather than simply forcing the user to open a new window.

Demo/Download

For anyone who missed it, here is another link to the online demo:

View/download the external links demo »

Wrapping Up…

So there you have it. Now go forth and please The Great Validator and The Great Usurpers. Much thanks to Kevin Yank of SitePoint.com for his original article and to Jeff Starr of Perishable Press for hosting this one. Also, a huge thank you to all User Experience Experts and Advocates for unwittingly and unfairly playing the role of the villain in my little story. I hope you’ll forgive my having a little fun at your expense and not rush out to buy a Bill Brown voodoo doll.

About the Author
Bill is the creator of WebDevelopedia.com and is an active member of several discussion lists, including the CSS Discussion List. When not online, Bill can be found enjoying the company of his girlfriend, Jessica and their dog, Leica (she doesn’t have a web site).
SAC Pro: Unlimited chats.

18 responses to “Targeting External Links Intelligently”

  1. Hi!
    Should links open in new windows? is an interesting post about this topic from SmashingMagazine.

  2. Excellent contribution to the subject, Bleyder! Will certainly give it a read.. Thanks! :)

  3. On my XHTML 1.0 Strict site I used the following in the anchor of external links to make them open in new windows, and it validates works exactly as tartet=”_blank” did.

    onclick="target='newwindow'"

    An example of it in use can be found on the facebook and twitter links near the top of my homepage. However, your script allows for more user control and does not require special tags on every external link, so some webmasters may prefer one method or the other.

  4. Bill Brown 2009/01/20 10:42 am

    Without a doubt, the issue of opening links in new windows is controversial, at best. The idea with this script was to share new window controls between the developer and the user.

    We don’t want to override the user’s wishes. As the SmashingMagazine article says, some users prefer to right-click into new tabs (like me), and some prefer a more single-window approach to surfing.

    In the perfect world, all users would use a compliant browser, know exactly what the browser can do and clients would never, ever ask for content to be loaded into a new window. This world may exist somewhere, but it’s certainly not where my mail get delivered.

    That being the case, we search out compromises. I think the idea of shared control, or new window “hinting” is a fair choice.

  5. I think this is an incredibly useful method, and a great solution to the age-old problem of whether or not to open external links as blank targets in new windows.

    Given the increasingly stylish UI-aesthetics of the whole Web-2.0 thing, I think a great way to improve the script and perhaps make it more widely adopted would be to replace the boring default popup dialogue box with something a little more subtle and stylish.

    For example, the alert message could take the form of a tooltip-like speech balloon that appears upon hovering over a link; then, within the tooltip alert, there would be the various options presented via simple links. I have seen some incredibly sharp-looking JS link hover-popups that would, I think, provide further incentive for people to employ the technique.

  6. In a perfect world, browsers would let users have an option to open all off-site links in new windows/tabs while keeping the links pointing to the same site open in the same window/tab. I don’t see that happening anytime soon, so this solution is the best so far (granted, with the cookie solution). Thanks for posting a jQuery solution to this.

  7. with all due respect to the problem and your attempts to provide a valid option for users, I find the popup modal window to be very annoying. If the page had a list of links to external sites I would quickly tire of this page behavior.

    My opinion could be wrong. I’d want to do user testing with a variety of users to see what they think.

  8. Another great article man; loved the intro. A side line question though while you mentioned _blank was not ‘strictly’ xhtml; how about the no-follow attributes etc. do they adhere to the principles?

  9. Bill Brown 2009/01/21 8:11 am

    @Jeff
    Completely agree. jQueryUI has a couple of nice options for this, but this article was already covering enough, so I let that pass for this case. Excellent point though.

    @John
    I totally agree. I even mentioned sort of as an aside in the article. Maybe that was an oversight in browser development?

    @Andrew
    I personally would not leave the modal prompt in place if I was visiting a website. I would select one of the other options (visible in the demo).

    @Donace
    Thanks! The rel attributes are valid attributes in XHTML. Most scripts use rel=”external” as a method of “tagging” the link as an external resource. Then, we can isolate those links with a DOM walk and add the target=”_blank” behind the scenes. It’s totally cheating, as a quick check of the generated content with Firefox’s awesome Web Developer toolbar would quickly show that the JavaScript generated content is not valid XHTML.

  10. an alternate solution: when the user hovers the pointer over the link, a small menu would appear, with 2 options: open in new window, open in same window

  11. […] that is completely horrible.

    Dan is on the money in my opinion. Generally what I do is add small link images that will open it in a new window. This seems to be the nicest way to do it in my opinion. Your way is obtrusive and would very quickly annoy users.

    ~Alex

    [ admin note: edited for language ]

  12. Bill Brown 2009/01/22 7:46 am

    @Alex:
    Maybe I’m missing something; I don’t understand what makes this obtrusive. If a user selects the global setting of “Open in New Window” or “Open in This Window” they would never receive another notice whatsoever. How is that obtrusive?

Comments are closed for this post. Something to add? Let me know.
Welcome
Perishable Press is operated by Jeff Starr, a professional web developer and book author with two decades of experience. Here you will find posts about web development, WordPress, security, and more »
Blackhole Pro: Trap bad bots in a virtual black hole.
Thoughts
I disabled AI in Google search results. It was making me lazy.
Went out walking today and soaked up some sunshine. It felt good.
I have an original box/packaging for 2010 iMac if anyone wants it free let me know.
Always ask AI to cite its sources. Also: “The Web” is not a valid answer.
All free plugins updated and ready for WP 6.6 dropping next week. Pro plugin updates in the works also complete :)
99% of video thumbnail/previews are pure cringe. Goofy faces = Clickbait.
RIP ICQ
Newsletter
Get news, updates, deals & tips via email.
Email kept private. Easy unsubscribe anytime.