Set a Cookie based on url Parameter

后端 未结 2 971
旧时难觅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:48

    First thing you need to fix is:

    if(url.indexOf('?src' + uni) = 1)
    

    should be (this checks that it exists at index 1):

    if(url.indexOf('?src=' + uni) === 1)
    

    or (this checks it exists at all)

    if(url.indexOf('?src=' + uni) !== -1)
    

    Next, you need to set src to the uni and make it accessible to the entire site:

    document.cookie="src="+uni+"; path=/; domain=.myadmin.com";
    

    Adding the path=/ and domain=.myadmin.com will allow you to access the cookie at all paths on that domain, and the domain part lets it be accessible on all subdomains (i.e. www.myadmin.com as well as blog.myadmin.com, etc)

    so all together:

        function SetCookie() {
            var url = window.location.href;
            if(url.indexOf('?src='+uni) !== -1)
                document.cookie="src="+uni+"; path=/; domain=.myadmin.com";
        }
    

    Here is some basic info:

    http://www.w3schools.com/js/js_cookies.asp

    Or the more in depth, accurate documentation:

    https://developer.mozilla.org/en-US/docs/Web/API/Document/cookie

提交回复
热议问题