Set a Cookie based on url Parameter

后端 未结 2 952
旧时难觅i
旧时难觅i 2021-01-14 08:05

I need to set a cookie whenever a user clicks through one of our affiliate links and lands on our site with \"src=uni\" in the URL. The URLs will look something like this:

2条回答
  •  野的像风
    2021-01-14 08:42

    A few things here:

    function SetCookie() {
        var url = window.location.search;
        if(url.indexOf('?src=uni') !== -1)
            document.cookie="src=uni";
    }
    

    1) Use location.search to narrow down your range, not necessary, but less room for error,

    2) Use !== -1 to test the indexOf method. indexOf returns "-1" if it does not find a match. And "0" if it finds a match at the beginning of the string. The string is "zero indexed" which means the first character in the string is in position "0".

    3) Add the equal sign = along with your parameter name: src=.

    4) Also, use the string "uni" if that is what you're looking for, rather than a variable named uni. If "src" can be a variety of values, then we'll need to add some more logic to account for that.

    5) And when assigning to document.cookie use key/value pairs as in: key=value.

提交回复
热议问题