Created
May 18, 2017 17:25
-
-
Save AndyCouch/492a4838e22e599cff58fb9c93833855 to your computer and use it in GitHub Desktop.
DOM Scripting External Links
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function externalLinks() { | |
var domainList = ["mydomain.com", "mycdn.com"]; // Your domain(s). | |
// Links to anything on these domains are considered internal. | |
// Enclose each domain in quotes, separated by a comma. (e.g. "domain1", "domain2") | |
// You do not need to list sub-domains. This function already assumes all sub-domains | |
// are internal. | |
// Open external links in a new window? true = yes, false = no | |
var newWindow = true; | |
// Add a special class to external links? true = yes, false = no | |
var addClass = true; | |
// Class name for external links. | |
var extClass = "external"; | |
// Add a warning dialog to external links? true = yes, false = no | |
var addWarning = true; | |
// Text for warning dialog. | |
var warning = "You are about to leave my site."; | |
if (!document.getElementsByTagName) return false; | |
var anchorList = document.getElementsByTagName("a"); | |
var protocolStart = "^http[s]?:\/\/"; | |
var protocol = new RegExp(protocolStart, "i"); | |
var domains = ""; | |
for (var i=0; i < domainList.length; i++) { | |
domains += "(" + domainList[i] + ")"; | |
if (i < (domainList.length - 1)) { | |
domains += "|"; | |
} | |
} | |
var mySites = new RegExp(protocolStart + "([a-z0-9-\.]*\.)?" + domains, "i"); | |
for (var i=0; i < anchorList.length; i++) { | |
if (anchorList[i].href.match(protocol) && !anchorList[i].href.match(mySites)) { | |
if (newWindow) anchorList[i].setAttribute("target", "_blank"); | |
if (addClass) anchorList[i].className=extClass; | |
if (addWarning) anchorList[i].onclick=function() { | |
var leave = window.confirm(warning); | |
return leave; | |
} | |
} | |
} | |
} | |
window.onload=externalLinks; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This code snippet was originally created on February 25, 2007, so while it still works, it's a bit old now.