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

Open External Links as Blank Targets via Unobtrusive JavaScript

Beginning with this article, I am serving up a short series of unobtrusive JavaScript functions that I use to enhance the functionality of Perishable Press. In this post, I present a comprehensive JavaScript method of opening external links in new windows (or tabs, depending on the browser).

Blank Targets

One way of opening links in new windows is to insert the HTML target="_blank" attribute into all necessary anchor elements (<a href=""></a>). This method works well, but generates validation errors when used with XHTML-Strict doctypes. Here is an example for those who may be unfamiliar with the good ’ol blank-target attribute:

<a target="_blank" href="https://m0n.co/">Opens in new tab</a>

JavaScript Way

A better solution is to employ some unobtrusive JavaScript to progressively enhance your documents with “blank-target” functionality. Using the following code, 99% of your visitors (those with JavaScript) will enjoy external links opening in new windows, while the remaining 1% of your audience (those without JavaScript) will enjoy your site without even realizing they are missing out on those wonderful blank-targeted links. It’s a “win-win” situation ;)

To implement this unobtrusive, gracefully degradable strategy, simply replace any target="_blank" attributes with the XHTML-friendly rel="external" attribute. Using rel="external" is standards-compliant and thus completely valid, even for XHTML-Strict and XHTML-1.1 doctypes.

After you have prepared your external link anchors with rel="external" attributes, apply the following JavaScript either inline or externally. No additional editing or markup is required — grab, gulp, & go!

// Open External Links as Blank Targets via Unobtrusive JavaScript
// https://perishablepress.com/press/2007/11/20/open-external-links-as-blank-targets-via-unobtrusive-javascript/

function externalLinks() {
	if (!document.getElementsByTagName) return;
	var anchors = document.getElementsByTagName("a");
	for (var i=0; i<anchors.length; i++) {
		var anchor = anchors[i];
		if (
			anchor.getAttribute("href") && ( 
			anchor.getAttribute("rel") == "external" || 
			anchor.getAttribute("rel") == "external nofollow" || 
			anchor.getAttribute("rel") == "nofollow external" )
			)
		anchor.target = "_blank";
	}
}
window.onload = function() {
	externalLinks();
}

Other JavaScript methods for opening external links in new windows work only if the rel attribute is set to external. However, in many situations, especially when working with WordPress and its myriad plugins, external links are also tagged with additional properties, such as nofollow, for example. The code presented in this article opens all links with any of the following attributes in a new window (click links for demo):

Of course, by modifying and/or emulating the sequence of anchor.getAttribute() expressions, it is relatively (no pun intended) straightforward to trigger blank-target behavior for virtually any rel attribute.

About the Author
Jeff Starr = Designer. Developer. Producer. Writer. Editor. Etc.
Banhammer: Protect your WordPress site against threats.

23 responses to “Open External Links as Blank Targets via Unobtrusive JavaScript”

  1. “Open External Links as Blank Targets”

    It just feel so wrong !

    I can’t believe you advice us to use target=_blank links. It’s been highly debated that no one should force the user’s browser to behave differently.

    If a user wants to open a link in another tab, then he justs ask for it, by middle-clicking or by another way. It’s a very bad thing to impose him to open a new page (yes, in Safari, target=_blank does not create a new tab, but a new windows, even with tabs on)

    Aren’t you upset when a link does not behave as intended ?

  2. Perishable 2007/11/20 2:12 pm

    Well now, everybody just calm down..

    This article is meant for informational purposes only. The information and techniques presented here are intended to serve a particular need, not to advise or advocate any particular method of doing anything. If you re-read through the article, you will see that I never advise, only explain. I leave it up to the reader to decide whether it is necessary or not.

    You bring up a good point, though. Visitors should have control and be given the option of opening links in new windows or tabs. However, there are certain situations in which providing external links fosters usability and accessibility. For example, one of the few types of links that I like to have opened automatically in a new window are “theme-demonstration” links. Changing the WP theme requires cookies, alters the entire layout, and resets the page to the blog root. Unsuspecting visitors would be left dazed and confused with a single click if such links weren’t opened in a new window.

    What’s really crazy is that I care enough about web standards to even bother with an entire script for this purpose. Believe me, it would have been far easier to just take the lazy way out and slip in a few target="_blank" attributes here and there. After all, it’s only like four or five pages on the entire site that even use them!

  3. Rick Beckman 2007/11/20 2:48 pm

    Perishable: What if an external link uses XFN as well? For instance, its REL attribute may be equal to “external coworker” or “external sweetheart met.”

    Would the “or equals” method work in such cases, or would the JavaScript need to be changed to look for “external” among any number of possible REL entries?

  4. I think the script is just great. Writing XHTML Strict, I still want that for the sake of (many?) visitors some files open in a new window or tab. E.g. pdf and spreadsheets.

  5. Perishable 2007/11/20 5:08 pm

    Excellent point, Rick. Rather than writing out every possible rel attribute, we can use a regular expression to match virtually any instances of external. A few additional variables, including one for the regular expression, and we have something like:

    // match all instances of 'external'
    function externalLinks() {
         if (!document.getElementsByTagName) return;
         var anchors = document.getElementsByTagName("a");
         for (var i=0; i<anchors.length; i++) {
              var relative = anchor.getAttribute("rel");
              var pattern = /external/i;
              var anchor = anchors[i];
              if (anchor.getAttribute("href") && external.test(relative)) {
                   anchor.target = "_blank";
              }
         }
    }

    Also, notice the “i” after the regex (i.e., /external/i). This renders the string case-insensitive, providing a greater match sensitivity. Definitely no need for extraneous “or equals” statements. Thanks for the subtle reminder, btw ;)

  6. Rick Beckman 2007/11/20 5:14 pm

    Excellent. :)

  7. Perishable 2007/11/20 5:17 pm

    Harrie,

    You are absolutely correct, there are many genuinely valid reasons for employing externally opening web documents. In addition to the excellent examples you mention, there are also peripheral resources such as images, movies, and other multimedia content that definitely warrant their own window or tab. I agree that such functionality helps a majority of visitors. Thanks for the comment!

  8. That’s a great little piece Perishable – to add my voice to the chorus, there are definitely times when you want a document to open in a new window.

    Thanks for the idea!

  9. Perishable 2007/11/26 9:13 pm

    My pleasure! ;)

  10. This is great code but I was looking for a wordpress plugin. I figure others will find this who want a wordpress plugin so here’s what I found: http://wordpress.org/extend/plugins/blank-target-replacement/ The code may need to be tweaked to work like comment number five buts it’s easier than starting from scratch. Thanks!

  11. Exelent idea, thanks!
    But what if I want to give the new window specific size?
    Is it possible?

  12. Erik Vold 2008/12/03 3:05 am

    Hey,

    Nice script, I’ve made a little tweak, posted here: http://erikvold.com/blog/index.cfm/2008/12/3/open-external-links-as-blank-targets-via-unobtrusive-javascript-microformat-safe-version

    I did two things:

    1. I don’t make target=”_blank” if the target attribute already exists; for example say it was already target=”_parent”..

    2. I use a reg exp to check for “external” in the rel tag, but this reg exp will not match “notexternal”, it would not match ‘xyz-external-123’, and a bunch of other unacceptable strings. This accounts for rel tag microformats.

    Erik Vold

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 »
BBQ Pro: The fastest firewall to protect your WordPress.
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.