NineCattoRules
NineCattoRules

Reputation: 2428

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);
}

Upvotes: 0

Views: 1501

Answers (1)

Mamdouh Saeed
Mamdouh Saeed

Reputation: 2324

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");
    }

Upvotes: 3

Related Questions