简体   繁体   English

如何使用Javascript检测外部链接

[英]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. 在我的网站内部,导航是使用Ajax进行的,仅当用户来自外部而不是来自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);
}

Here's short example using location.hostname vs document.referrer.split("/")[2] 这是使用location.hostnamedocument.referrer.split("/")[2]的简短示例

Note : snippet is running in iframe so it will alert External referrer 注意 :该代码段正在iframe中运行,因此会提醒External referrer

  var isExternal = document.referrer.split("/")[2] !== location.hostname; if (isExternal) { alert("External referrer"); } 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM