Redirect user to random URL from a list that shrinks upon each visit, then resets

Viewed 29

This JavaScript redirects the user to a random URL from a list for 30 days, then randomly assigns a different destination URL:

    

// List of URLs (two or more) for the experimental treatment and control groups.
var RedirectURLs = {
    "urls" : [
        { "url" : "http://www.aftonbladet.se/" },
        { "url" : "http://www.dn.se/" },
        { "url" : "http://www.svd.se/" }
    ]
}

// Count the number of URLs in list.
var Groups = RedirectURLs.urls.length;

// Randomize number and get the corresponding index for the URL in list.
var gotoUrl = RedirectURLs.urls[GetRandomNumber(Groups)].url

// Perform redirection.
if (window.location.search == "?debug") {
    // Debug mode: If user supplies a ?debug querystring,
    // then only show the redirect URL, but don't actually redirect.
    document.write("Redirect URL: " + gotoUrl);
} else {
    // Redirect the user to the new URL.
    document.location = gotoUrl;
}

// Perform randomization and save it to a cookie.
function GetRandomNumber(Groups) {
    // Has cookie been set?
    var rndIndex = null;
    if (GetCookie() != "") {
        // Yes, get randomization from cookie.
        rndIndex = GetCookie()
    } else {
        // No, set random value to cookie.
        rndIndex = Math.floor((Math.random() * Groups));
        SetCookie(rndIndex, 30) // Set cookie for 30 days.
    }
    return rndIndex
}

// Set cookie with randomization value.
function SetCookie(CookieValue, DaysUntilExpire) {
    var d = new Date();
    d.setTime(d.getTime() + (DaysUntilExpire * 24 * 60 * 60 * 1000));
    document.cookie = "rnd=" + CookieValue + ";expires=" + d.toUTCString();
}

// Get cookie with randomization value. Return empty string if not set.
function GetCookie() {
    var ca = document.cookie.split(';');
    for(var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') c = c.substring(1);
        if (c.indexOf("rnd=") == 0) return c.substring(4, c.length);
    }
    return "";
}
    

How can the code be modified so that instead of storing a cookie that tells the browser to keep going to the same URL for 30 days, instead, the cookie is used to cumulatively track what's already been visited, so the user is redirected to new URL's until each one from list has been visited and tracking starts all over?

For example:

  • if cookie is empty, user is randomly redirected to link 2 from a list of 4 url's
  • cookie stores [1,3,4]
  • next visit, user is randomly redirected to link 4
  • cookie deletes 4 to become [1,3]
  • next visit, user is randomly redirected to link 3
  • cookie deletes 3 to become 1
  • next visit, user is redirected to link 1
  • cookie clears
  • next visit, cookie is empty, so user randomly redirects to link from full list
0 Answers
Related