Skip to content

Instantly share code, notes, and snippets.

@kfriend
Last active December 20, 2015 10:09
Show Gist options
  • Save kfriend/6113222 to your computer and use it in GitHub Desktop.
Save kfriend/6113222 to your computer and use it in GitHub Desktop.
JavaScript: Open external links and specific file types in a new tab/window
$(document).ready(function() {
/*-------------------------------------------------------------------
| Force external links and specific files to open in a new window/tab
*-------------------------------------------------------------------*/
var externalProtocolRegex = /^https?:\/\//i;
var externalRegex = (window.location.protocol + '//' + window.location.hostname).replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
externalRegex = new RegExp('^(\/\/|' + externalRegex + ')');
var fileRegex = /\.pdf$/;
$('a[href!=""]').not('[target=_blank]').click(function(event) {
var href = $(event.target).closest('a').attr('href');
if (
href &&
(
// Is it a protocol-relative URL?
href.substring(0, 2) === '//' ||
(
// Does it even start with something that would indicate an external URL?
// Checking for this eliminates relative and absolute path hrefs.
href.match(externalProtocolRegex) &&
// Does the provided domain match this site's?
!href.match(externalRegex)
) ||
// Is it a specific file type?
href.match(fileRegex)
)
) {
event.preventDefault();
window.open(href, '_blank');
return;
}
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment