Javascript 检查推荐人

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2031362/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-22 22:29:11  来源:igfitidea点击:

Checking the referrer

javascriptreferrer

提问by Ben Shelock

I'm using this to check if someone came from Reddit, however it doesn't work.

我用它来检查是否有人来自 Reddit,但它不起作用。

var ref = document.referrer;
if(ref.match("/http://(www.)?reddit.com(/)?(.*)?/gi"){
    alert('You came from Reddit');
} else {
    alert('No you didn\'t');
}

Suggestions on the regular expression are most welcome too.

也欢迎对正则表达式提出建议。

回答by gnarf

Try this:

尝试这个:

if (ref.match(/^https?:\/\/([^\/]+\.)?reddit\.com(\/|$)/i)) {
  alert("Came from reddit");
}

The regexp:

正则表达式:

/^           # ensure start of string
 http        # match 'http'
 s?          # 's' if it exists is okay
 :\/\/       # match '://'
 ([^\/]+\.)? # match any non '/' chars followed by a '.' (if they exist)
 reddit\.com # match 'reddit.com'
 (\/|$)      # match '/' or the end of the string
/i           # match case-insenitive

回答by Skilldrick

Close your ifparen...

关闭你的if家长...

回答by TimSmith-Aardwolf

I've been using an alternative to RegEx by looking for the domain in the referrer

我一直在通过在引用中查找域来使用 RegEx 的替代方法

if (document.referrer.indexOf('reddit.com') >= 0) { alert('They came from Reddit.com'); }

EDIT: As thekingoftruth points out that doesn't work if reddit.com is included in an URL parameter so I've extended it a little. I've also added toLowerCase() as I spotted that in the RegExp above.

编辑:正如 thekingoftruth 指出的那样,如果 reddit.com 包含在 URL 参数中是行不通的,所以我对其进行了一些扩展。我还添加了 toLowerCase(),因为我在上面的 RegExp 中发现了这一点。

if (document.referrer.indexOf('?') > 0){
    if (document.referrer.substring(0,document.referrer.indexOf('?')).toLowerCase().indexOf('reddit.com') >= 0){
    alert('They came from Reddit');
    }
} else {
    if (document.referrer.toLowerCase().indexOf('reddit.com') > 0){
            alert('They came from Reddit');
    }
}

回答by Gumbo

Try this:

尝试这个:

ref.match(new RegExp("^http://(www\.)?reddit\.com/", "i"))

Or:

或者:

ref.match(/^http:\/\/(www\.)?reddit\.com\//i)

回答by GeniusGeek

I would use this, wouldn't it be a lesser and simply way?

我会使用这个,这不是一种更简单的方法吗?

  var referral= document.refferer;
   If(referral.includes("www.reddit.com"){
  alert("you came from reddit");
   }
     else{
    alert("you didn't come from reddit");
       {

回答by GeniusGeek

Use var ref = document.referer; // ONE R instead of TWO

使用 var ref = document.referer; // 一个 R 而不是两个