Member Login:


Get (read/retrieve) a cookie with JavaScript

Document Reference: TN201708002 - Rev: 4.02 - Last Update: 22-07-2019 20:30 GMT - Downloaded: 28-Apr-2024 04:41 GMT

The mcrSf.cookieGet() method requires one argument and returns a string value.

The required argument defines the cookie name. There is no option to specify the path that the cookie belongs to. A path was specified at the time of setting the cookie and cookies can only be accessed from files and subfolders within this path.

Please Note: Due to security issues and other problems, Google Chrome and other popular browsers have disabled storing cookies for local files. Cookies can only be stored and retrieved for files that are served from a webserver.

Parameters

ParameterTypeDescription
cookieNameStringThe name of the cookie.

Return Value

TypeDescription
StringThe stored value of the cookie.
undefinedThe method will return undefined if the requested cookie can not be read.

The Stand-Alone Function

Below code is ready for copy/paste and will work just fine on it's own, without linking the mcrSf library file.

 function cookieGet(cookieName) {
    cookieName += "=";
    var cookieArray = decodeURIComponent(document.cookie).split(';');
    for(var i = 0; i < cookieArray.length; i++) {
        var cookieEl = cookieArray[i].replace(/^\s+|\s+$/gm,'');
        if (cookieEl.substring(0, cookieName.length) == cookieName) {
            return cookieEl.substring(cookieName.length, cookieEl.length);
        }
    }
    return undefined;
}

The mcrSf Library Method

 /**
* Get (read) a cookie
* @version 0.1
* @param {String} cookieName - the name of the cookie
* @return {String} - value of cookie
*
* STRATEGY: Read a value from the cookie property from the document object
*/
cookieGet: function(cookieName) {
    cookieName += "=";
    var cookieArray = decodeURIComponent(document.cookie).split(';');
    for(var i = 0; i < cookieArray.length; i++) {
        var cookieEl = cookieArray[i].replace(/^\s+|\s+$/gm,'');
        if (cookieEl.substring(0, cookieName.length) == cookieName) {
            return cookieEl.substring(cookieName.length, cookieEl.length);
        }
    }
    return undefined;
}

Version History

Revision
Date
Details
0.1
05-Aug-17
First release, cookieGet().

This website uses cookies to give you the best experience on our website, to personalise content and to analyse our website traffic. Some cookies may have been set already. To find out more about our use of cookies you can visit our Privacy Statement. By browsing this website, you agree to our use of cookies.

Hide this message