How to have all external links on my website raise a confirm

I am trying to have all external links on my website raise a confirm saying “You are being redirected to an external site.” I know how to write the JS to check for if a link is external and how to raise the confirm, but is there a way I can apply this to every link in my site without going through individually? The links will always have the format <a href=URL> Link </a>. An angular script would check if the URL subdomain is the same as my site, and if not it will add onclick=return confirm('You will now be redirected to an exteral site') and target="_blank" to the link HTML.

Answer

  1. It can be achieved by the regex matching.
  2. Instead of adding multiple event listeners, single event listener can be added on the document object and detect the external links as follows. It will give more efficiency.

For reference, Handling events for multiple elements in a single listener

var regexp = /https?://(www.){0,1}((?:[wd-]+.)+[wd]{2,})/i;
function isExternal(url)
{
    return regexp.exec(location.href)[2] !== regexp.exec(url)[2];
}

document.addEventListener("click",function(){
    if(event.target.tagName.toLowerCase()==="a")
    {
        if(isExternal(event.target.href))
        {
            if(confirm("Redirecting to an external site...."))
            {
                console.log("Going to external site...");
                return;
            }
            else
            {
                event.preventDefault();
                return;
            }
        }
        else
        {
            console.log("Internal URL Clicked.")
        }
    }
});
<a href="https://www.google.com" target="_blank">External Site 1</a> - https://www.google.com<br>
<a href="https://www.stackoverflow.com" target="_blank">External Site 2</a> - https://www.stackoverflow.com<br>
<a href="http://www.facebook.com" target="_blank">External Site 3</a> - http://www.facebook.com (Using HTTP)<br>
<a href="http://www.stacksnippets.net" target="_blank">Internal Site (Using HTTP)</a> - http://www.stacksnippets.net<br>
<a href="http://stacksnippets.net" target="_blank">Internal Site (without www.)</a> - http://stacksnippets.net<br>
<a href="/path/to/something" target="_blank">Internal reference</a> - /path/to/something (Internal reference)<br>

Thanks @pseudosavant for the regex.

Though @Luca’s answer works, the hostname is not supported in IE, Safari and Opera. Browser Compatibility for reference.