MDN’s new design is in Beta! A sneak peek:

Перевод не завершен. Пожалуйста, помогите перевести эту статью с английского.

Статья описывает получение и установка cookies связанных с текущим документом. Общая библиотека для работы с  cookies смотри simple cookie framework.


Чтение всех cookies связанных с текущим документом
allCookies = document.cookie;

Здесь строка allCookies содержит перечень всех cookies  разделенных точкой с запятой(key1=value1;key2=value2;).

В приведенном коде newCookie - строка в виде key=value(ключ=значение). Заметьте, у вас есть возможность установить/обновить лишь одну связку key=value за один раз используя этот метод.  Стоит отметить что:

  • Любой из ниже приведенных атрибутов опционально могут присутствовать в строке cookie. Атрибути должны идти после пары key=value и разделяться точкой с запятой.
    • When user privacy is a concern, It is important that any web app implementation will invalidate cookie data after a certain timeout and won't rely on the browser clearing session cookies
      One of the most beloved features of Firefox prevents session cookies from ever expiring 
      The same issue is also occuring with google chrome (and probably with other browsers offering similar features)

  • Строка value в cookie может использовать  encodeURIComponent(). Для обеспечения этого, строка не должна содержать запятые, точки с запятой или пробелы(которые запрещены в значении cookie ).
Примечание: Как вы могли увидеть из кода выше, document.cookie это accessor property  з нативними геттерами и сеттерами, и следавательно, это не data property с значением.  То что вы записываете не равно тому что считуюте. Все всегда проходить через JavaScript интерпиртатор.


Пример #1: Простое использование

document.cookie = "name=oeschger";
document.cookie = "favorite_food=tripe";
function alertCookie() {
<button onclick="alertCookie()">Show cookies</button>

document.cookie = "test1=Hello";
document.cookie = "test2=World";

var cookieValue = document.cookie.replace(/(?:(?:^|.*;\s*)test2\s*\=\s*([^;]*).*$)|^.*$/, "$1");

function alertCookieValue() {
<button onclick="alertCookieValue()">Show cookie value</button>

Пример #3: Выполнить операцию единожды

При использовании следующего кода, заменити все вхождения "doSomethingOnlyOnce"(наименование cookie) на другое имя.

function doOnce() {
  if (document.cookie.replace(/(?:(?:^|.*;\s*)doSomethingOnlyOnce\s*\=\s*([^;]*).*$)|^.*$/, "$1") !== "true") {
    alert("Do something here!");
    document.cookie = "doSomethingOnlyOnce=true; expires=Fri, 31 Dec 9999 23:59:59 GMT";
<button onclick="doOnce()">Only do something once</button>

function resetOnce() { 
  document.cookie = "doSomethingOnlyOnce=; expires=Thu, 01 Jan 1970 00:00:00 GMT";
<button onclick="resetOnce()">Reset only once cookie</button>


It is important to note that the path attribute does not protect against unauthorized reading of the cookie from a different path. It can be easily bypassed using the 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 the cookie 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 = "" + 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.


  • 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.
  • RFC 2965 (Section 5.3, "Implementation Limits") specifies that there should be no maximum length of a cookie's key or value size, and encourages implementations to support arbitrarily large cookies. Each browser's implementation maximum will necessarily be different, so consult individual browser documentation.

The reason of the syntax of the document.cookie accessor property is due to the client-server nature of cookies, which differs from other client-client storage methods (like, for instance, localStorage):

HTTP/1.0 200 OK
Content-type: text/html
Set-Cookie: cookie_name1=cookie_value1
Set-Cookie: cookie_name2=cookie_value2; expires=Sun, 16 Jul 3567 06:23:41 GMT

[content of the page here]
The client sends back to the server its cookies previously stored
GET /sample_page.html HTTP/1.1
Cookie: cookie_name1=cookie_value1; cookie_name2=cookie_value2
Accept: */*

Использование относительных ссылок в параметре path

The path parameter of a new cookie can accept only absolute paths. If you want to use relative paths, therefore, you need to convert them. The following function can translate relative paths to absolute paths. It is a general-purpose function, but can be of course successifully used for the path parameter of a new cookie, as well.

|*|  :: Translate relative paths to absolute paths ::
|*|  The following code is released under the GNU Public License, version 3 or later.

function relPathToAbs (sRelPath) {
  var nUpLn, sDir = "", sPath = location.pathname.replace(/[^\/]*$/, sRelPath.replace(/(\/|^)(?:\.?\/+)+/g, "$1"));
  for (var nEnd, nStart = 0; nEnd = sPath.indexOf("/../", nStart), nEnd > -1; nStart = nEnd + nUpLn) {
    nUpLn = /^\/(?:\.\.\/)*/.exec(sPath.slice(nEnd))[0].length;
    sDir = (sDir + sPath.substring(nStart, nEnd)).replace(new RegExp("(?:\\\/+[^\\\/]*){0," + ((nUpLn - 1) / 3) + "}$"), "/");
  return sDir + sPath.substr(nStart);
Sample usage
/* Let us be in /en-US/docs/Web/API/document.cookie */

// displays: /en-US/docs/Web/API/document.cookie

// displays: /en-US/docs/Web/API/

// displays: /en-US/docs/Web/Guide/API/DOM/Storage

// displays: /en-US/docs/Firefox

// displays: /en-US/docs/Firefox

Relative expiration-date: numeric examples

If you don't want to use an absolute date for the end parameter, here you can find some numeric examples of expiration-dates relative to the moment of storage of the cookie:

docCookies.setItem("mycookie1", "myvalue1", 864e2, "/"); // this cookie will expire in one DAY
docCookies.setItem("mycookie2", "myvalue2", 6048e2, "/"); // this cookie will expire in one WEEK
docCookies.setItem("mycookie3", "myvalue3", 2592e3, "/"); // this cookie will expire in one MONTH (30 days)
docCookies.setItem("mycookie4", "myvalue4", 31536e3, "/"); // this cookie will expire in one YEAR

Другие примеры

Example #5: Do something only once – a general library

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 (decodeURIComponent(document.cookie.replace(new RegExp("(?:(?:^|.*;)\\s*" + encodeURIComponent(sKey).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=\\s*([^;]*).*$)|^.*$"), "$1")) === "1") { return false; }
  fExec.apply(argc > 3 ? arguments[1] : null, argc > 4 ?, 2, argc - 2) : []);
  document.cookie = encodeURIComponent(sKey) + "=1; expires=Fri, 31 Dec 9999 23:59:59 GMT" + (bImplGlob || !arguments[argc - 1] ? "; path=/" : "");
  return true;
executeOnce(callback[, thisObject[, argumentToPass1[, argumentToPass2[, …[, argumentToPassN]]]]], identifier[, onlyHere])

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

The function to be executed (function).
thisObject Optional
The this object (object or null).
argumentToPass1, argumentToPass2, argumentToPassN Optional
The arguments of the callback function.
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) {

executeOnce(alertSomething, null, "Hello world!!!!", "alert_something");


Specification Status Comment
Document Object Model (DOM) Level 2 HTML Specification
Определение 'Document.cookie' в этой спецификации.
Рекомендация Initial definition

Совместимость браузеров

Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari (WebKit)
Basic support (Да) (Да) (Да) (Да) (Да)
Feature Android Firefox Mobile (Gecko) IE Phone Opera Mobile Safari Mobile
Basic support (Да) (Да) (Да) (Да) (Да)

Смотрите также 

Метки документа и участники

 Внесли вклад в эту страницу: beautifulSuicide, ykshatroff, c01nd01r
 Обновлялась последний раз: beautifulSuicide,