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…
- It did not check form action attributes
- 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 quick breakdown…
- a[href*=”://“] and form[action*=”://“] matches the elements where a full url has been specified
- .not($(‘a[href*=”://’+location.host+'”]’)) excludes all matched items that include the current host (eg: http://www.robertmullaney.com/)
- 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.
What if, the link didn’t have the beginning “http://”? i mean, that’s a problem if I create a website with user input.
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”
Furthermore, if you are accepting user input, you should be filtering to prevent XSS and possibly auto-linking if desired.