Set the cookie based on the URL.

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

Cookie creation function:

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


Can someone please help me by telling me where am I going wrong creating this cookie based on request parameters?


source to share

2 answers

Several things here:

function SetCookie() {
    var url =;
    if(url.indexOf('?src=uni') !== -1)


1) Use

to narrow the range, not necessary, but less room for error,

2) Use !== -1

to test the method indexOf

. indexOf

returns "-1" if no match is found. And "0" if it finds a match at the beginning of the line. The string is "zero indexed", which means that the first character in the string is at position "0".

3) Add an equal sign =

, along with your name parameter: src=


4) Also use the string "uni" if that's what you are looking for, not a named variable uni

. If "src" can be multiple values, then we will need to add some more logic to account for this.

5) And when appointing document.cookie

use key / value pairs, as in: key=value




The first thing you need to fix:

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 out at all)

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


Then you need to set src to uni and make it site-wide available:

document.cookie="src="+uni+"; path=/;";


Adding path = / and domain = will allow you to access the cookie on all paths in that domain, and part of the domain will allow it to be accessible on all subdomains (e.g. 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=/;";


Here are some basic details:

Or in more detail, the exact documentation:



All Articles