Handling External Links using JavaScript

arp14 JavaScript, Tutorial Tags: , , , , , , 0

External Links Handler is always good choice to alert your users when they clicks on External Links (link that outside of your website). It is also useful to be legal. If your users clicks on a external link,
you can alert them – they are going out, you won’t be responsible of any content on that external link and ask for their confirmation. Doing this is very simple using JavaScript built-in confirm() function.

External Links Handler Script

window.onload = function () {
	var links = document.getElementsByTagName('A');
	var msg = "We will not be responsible for any content outside. Are you sure?";
	for (var i=0; i<links.length; i++) {
		links[i].onclick = function () {
			if(this.toString().indexOf("w3epic.com") < 0) {
				if (!this.getAttribute('target')) this.setAttribute('target','_blank');
				if(!confirm(msg)) return false;
			}
		}
	}
}

In the script above, we’re calling a standalone function on windows.onload event. Then we’re looping through all anchor tags or links.
Then clicking on each link, we’re calling another standalone function and setting a custom alert message withing it. After that we’re checking each link, –
if each one contains your domain / site name within it or not. If it do not contain your domain / site name, then we got the link as a external link. In additionally,
we’re also checking if the external link has a attribute name “target”, if not, then we’re setting it’s target attribute to “_blank” to make external link open in
new tab or window whenever someone clicked on it. Then finally we’re asking user for confirmation. If user do not confirm, then it returns false which will prevent
its default action – to go to external links.

Need help? Having problem? Just comment below and give your feedback, I’ll be back to you ASAP – Thanks.

Leave a Reply

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