Checking the referrer

后端 未结 6 1344
情书的邮戳
情书的邮戳 2020-12-02 07:51

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

var ref = document.referrer;
if(ref.match(\"/http://(www.)?reddit.com(/)?(.*)         


        
相关标签:
6条回答
  • 2020-12-02 08:06

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

    0 讨论(0)
  • 2020-12-02 08:09

    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
    
    0 讨论(0)
  • 2020-12-02 08:14

    Try this:

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

    Or:

    ref.match(/^http:\/\/(www\.)?reddit\.com\//i)
    
    0 讨论(0)
  • 2020-12-02 08:18

    Close your if paren...

    0 讨论(0)
  • 2020-12-02 08:19

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

    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.

    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');
        }
    }
    
    0 讨论(0)
  • 2020-12-02 08:29

    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");
           {
    
    0 讨论(0)
提交回复
热议问题