SimonLeCat SimonLeCat - 1 month ago 8
Javascript Question

How can I detect an external link with Javascript

I have this simple function

setTimeout(function() {
$('.playthis').trigger('click');
},10);


Inside my website the navigation is made with Ajax, I need to trigger this function only if the user comes from outside not from Ajax. Is it possible?

I tried this

var ref = document.referrer;
if (ref.match(/^https?:\/\/([^\/]+\.)?example\.com(\/|$)/i)) {
//nothing
} else {
setTimeout(function() {
$('.playthis').trigger('click');
},10);
}

Answer

Here's short example using location.hostname vs document.referrer.split("/")[2]

Note: snippet is running in iframe so it will alert External referrer

    var isExternal = document.referrer.split("/")[2] !== location.hostname;

    if (isExternal) {
      alert("External referrer");
    }