IMPROVED: Open all external links in a new window using jQuery

In the original post I covered how to use jQuery to automatically make external links open in a new window. The method however was slightly flawed in my opinion since…

  1. It did not check form action attributes
  2. It assumed ANY link starting with “http[s]://” was external

Here is my new and improved method for making all external site links open in a new window. It now includes form tags, one less selector for secure and non-secure link urls, AND excludes any of those which link to an internal page where the full url may have been specified.

$('a[href*="://"], form[action*="://"]').not($('a[href*="://'+location.host+'"]')).attr('target','_blank');

A quick breakdown…

  1. a[href*=”://“] and form[action*=”://“] matches the elements where a full url has been specified
  2. .not($(‘a[href*=”://’+location.host+'”]’)) excludes all matched items that include the current host (eg: http://www.robertmullaney.com/)
  3. finally we update the target attribute of the the remaining links open in a new window

Why this is important:

Once you have a user on your site, the worst thing you can do is send them away. Also, you will easily annoy them if all links open in new windows and cause them to leave anyhow. This way, only the links that pull them away from site site are opened in new windows. When they are done on the external sites, they close the browser and there your site remains.

3 thoughts on “IMPROVED: Open all external links in a new window using jQuery

  1. aritra

    What if, the link didn’t have the beginning “http://”? i mean, that’s a problem if I create a website with user input.

    Reply
    1. admin Post author

      To be considered an external link (which is what my post covered), it must contain a protocol (http://, ftp://, etc). Without a protocol it is treated an internal link.

      eg: linking to “www.somedomain.com” instead of “http://www.somedomain.com” from “www.mydomain.com” would result in “http://www.mydomain.com/www.somedomain.com”

      Reply
    2. admin Post author

      Furthermore, if you are accepting user input, you should be filtering to prevent XSS and possibly auto-linking if desired.

      Reply

Leave a Reply to aritra Cancel reply

Your email address will not be published. Required fields are marked *