Set a Cookie based on url Parameter

故事扮演 提交于 2019-12-01 05:47:04

问题


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:

http://www.myadmin.com?src=uni&utm_source=uni&utm_content=[publisher_ID]

Function to create cookie:

 function SetCookie() {
            var url = window.location.href;
            if(url.indexOf('?src' + uni) = 1)
                document.cookie="QueryCookie";
    }

Can somebody help me by telling where I am going wrong in creating this Cookie based on query parameters?


回答1:


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.




回答2:


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



来源:https://stackoverflow.com/questions/29804219/set-a-cookie-based-on-url-parameter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!