aboutsummaryrefslogtreecommitdiff
path: root/files/ru/conflicting/web/api/window/localstorage/index.html
blob: 50b03e48d3c45b1f64b9e7ee154bde32d63cb36d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
---
title: LocalStorage
slug: conflicting/Web/API/Window/localStorage
translation_of: Web/API/Window/localStorage
translation_of_original: Web/API/Web_Storage_API/Local_storage
original_slug: Web/API/Storage/LocalStorage
---
<p><code>localStorage</code> это аналог <code><a href="/en-US/docs/Web/API/sessionStorage">sessionStorage</a></code>, с некоторыми same-origin правилами, но значения хранятся постоянно (в отличии от sessions). <code>localStorage</code> появился в Firefox 3.5.</p>

<div class="note"><strong>Примечание:</strong> Когда браузер переходит в режим приватного просмотра, создается новое временное хранилище. Изначально оно пустое. После выхода из режима приватного просмотра временное хранилище очищается.</div>

<pre class="brush:js" style="font-size: 14px;">// Сохраняет данные в текущий local store
localStorage.setItem("username", "John");

// Извлекает ранее сохраненные данные
alert( "username = " + localStorage.getItem("username"));</pre>

<p class="note"><code>localStorage</code>'s позволяет постоянно хранить некоторую полезную информацию, включая счетчики посещения страницы, как показано в примере <a href="http://codepen.io/awesom3/pen/Hlfma">this tutorial on Codepen</a>.</p>

<h4 id="Совместимость" style="line-height: 18px; font-size: 1.28571428571429rem;">Совместимость</h4>

<p><code>Storage</code> objects недавно добавлен в стандарт. Он может отсутствовать в некоторых браузерах. Вы можете работать с этой технологией добавив в страницу один из двух скриптов, которые представлены ниже. <code>localStorage</code> object реализуется программно, если нет встроенной реализации.</p>

<p>Этот алгоритм является точной имитацией <code>localStorage</code> object, но для хранения использует cookies.</p>

<pre class="brush:js" style="font-size: 14px;">if (!window.localStorage) {
  Object.defineProperty(window, "localStorage", new (function () {
    var aKeys = [], oStorage = {};
    Object.defineProperty(oStorage, "getItem", {
      value: function (sKey) { return sKey ? this[sKey] : null; },
      writable: false,
      configurable: false,
      enumerable: false
    });
    Object.defineProperty(oStorage, "key", {
      value: function (nKeyId) { return aKeys[nKeyId]; },
      writable: false,
      configurable: false,
      enumerable: false
    });
    Object.defineProperty(oStorage, "setItem", {
      value: function (sKey, sValue) {
        if(!sKey) { return; }
        document.cookie = escape(sKey) + "=" + escape(sValue) + "; expires=Tue, 19 Jan 2038 03:14:07 GMT; path=/";
      },
      writable: false,
      configurable: false,
      enumerable: false
    });
    Object.defineProperty(oStorage, "length", {
      get: function () { return aKeys.length; },
      configurable: false,
      enumerable: false
    });
    Object.defineProperty(oStorage, "removeItem", {
      value: function (sKey) {
        if(!sKey) { return; }
        document.cookie = escape(sKey) + "=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/";
      },
      writable: false,
      configurable: false,
      enumerable: false
    });
    Object.defineProperty(oStorage, "clear", {
      value: function () {
        if(!aKeys.length) { return; }
        for (var sKey in aKeys) {
          document.cookie = escape(sKey) + "=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/";
        }
      },
      writable: false,
      configurable: false,
      enumerable: false
    });
    this.get = function () {
      var iThisIndx;
      for (var sKey in oStorage) {
        iThisIndx = aKeys.indexOf(sKey);
        if (iThisIndx === -1) { oStorage.setItem(sKey, oStorage[sKey]); }
        else { aKeys.splice(iThisIndx, 1); }
        delete oStorage[sKey];
      }
      for (aKeys; aKeys.length &gt; 0; aKeys.splice(0, 1)) { oStorage.removeItem(aKeys[0]); }
      for (var aCouple, iKey, nIdx = 0, aCouples = document.cookie.split(/\s*;\s*/); nIdx &lt; aCouples.length; nIdx++) {
        aCouple = aCouples[nIdx].split(/\s*=\s*/);
        if (aCouple.length &gt; 1) {
          oStorage[iKey = unescape(aCouple[0])] = unescape(aCouple[1]);
          aKeys.push(iKey);
        }
      }
      return oStorage;
    };
    this.configurable = false;
    this.enumerable = true;
  })());
}
</pre>

<div class="note"><strong>Примечание:</strong> Максимальный размер данных, которые могут быть сохранены, ограничен возможностями cookies. Используйте functions <code>localStorage.setItem()</code> и <code>localStorage.removeItem()</code> для добавления, изменения, или удаления ключа. Использование прямого присвоения <code>localStorage.yourKey = yourValue;</code> и <code>delete localStorage.yourKey;</code> для установки и удаления ключа <strong>не безопасно с этим кодом</strong>. Вы также можете изменить это имя (вместо window.localStorage прописать другое имя) и использовать объект для управления document's cookies, не обращая внимания на localStorage object.</div>

<div class="note"><strong>Примечание:</strong> Если изменить строку <code style="background: rgb(204, 204, 204);">"; expires=Tue, 19 Jan 2038 03:14:07 GMT; path=/"</code> на: <code style="background: rgb(204, 204, 204);">"; path=/"</code> (и изменить имя объекта), он превратится в <code>sessionStorage</code> polyfill больше, чем в <code>localStorage</code> polyfill. Однако эта реализация будет хранить общие значения для всех вкладок и окон браузера (and will only be cleared when all browser windows have been closed), в то время как полностью совместимая <span style="font-family: 'Courier New','Andale Mono',monospace; line-height: normal;">sessionStorage</span><span style="line-height: 1.5em;"> реализация хранит значения</span><span style="line-height: 1.5em;"> to the current browsing context only.</span></div>

<p>Here is another, less exact, imitation of the <code>localStorage</code> object. It is simpler than the previous one, but it is compatible with old browsers, like Internet Explorer &lt; 8 (<strong>tested and working even in Internet Explorer 6</strong>). It also makes use of cookies.</p>

<pre class="brush:js" style="font-size: 14px;">if (!window.localStorage) {
  window.localStorage = {
    getItem: function (sKey) {
      if (!sKey || !this.hasOwnProperty(sKey)) { return null; }
      return unescape(document.cookie.replace(new RegExp("(?:^|.*;\\s*)" + escape(sKey).replace(/[\-\.\+\*]/g, "\\$&amp;") + "\\s*\\=\\s*((?:[^;](?!;))*[^;]?).*"), "$1"));
    },
    key: function (nKeyId) {
      return unescape(document.cookie.replace(/\s*\=(?:.(?!;))*$/, "").split(/\s*\=(?:[^;](?!;))*[^;]?;\s*/)[nKeyId]);
    },
    setItem: function (sKey, sValue) {
      if(!sKey) { return; }
      document.cookie = escape(sKey) + "=" + escape(sValue) + "; expires=Tue, 19 Jan 2038 03:14:07 GMT; path=/";
      this.length = document.cookie.match(/\=/g).length;
    },
    length: 0,
    removeItem: function (sKey) {
      if (!sKey || !this.hasOwnProperty(sKey)) { return; }
      document.cookie = escape(sKey) + "=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/";
      this.length--;
    },
    hasOwnProperty: function (sKey) {
      return (new RegExp("(?:^|;\\s*)" + escape(sKey).replace(/[\-\.\+\*]/g, "\\$&amp;") + "\\s*\\=")).test(document.cookie);
    }
  };
  window.localStorage.length = (document.cookie.match(/\=/g) || window.localStorage).length;
}
</pre>

<div class="note"><strong>Note:</strong> The maximum size of data that can be saved is severely restricted by the use of cookies. With this algorithm, use the functions <code>localStorage.getItem()</code><code>localStorage.setItem()</code>, and <code>localStorage.removeItem()</code> to get, add, change, or remove a key. The use of method <code>localStorage.yourKey</code> in order to get, set, or delete a key <strong>is not permitted with this code</strong>. You can also change its name and use it only to manage a document's cookies regardless of the localStorage object.</div>

<div class="note"><strong>Note:</strong> By changing the string <code style="background: rgb(204, 204, 204);">"; expires=Tue, 19 Jan 2038 03:14:07 GMT; path=/"</code> to: <code style="background: rgb(204, 204, 204);">"; path=/"</code> (and changing the object's name), this will become a <code>sessionStorage</code> polyfill rather than a <code>localStorage</code> polyfill. However, this implementation will share stored values across browser tabs and windows (and will only be cleared when all browser windows have been closed), while a fully-compliant <span style="font-family: 'Courier New','Andale Mono',monospace; line-height: normal;">sessionStorage</span><span style="line-height: 1.5em;"> implementation restricts stored values to the current browsing context only.</span></div>

<h4 id="Compatibility_and_relation_with_globalStorage" style="line-height: 18px; font-size: 1.28571428571429rem;">Compatibility and relation with globalStorage</h4>

<p class="note"><code>localStorage</code> is also the same as <code>globalStorage[location.hostname]</code>, with the exception of being scoped to an HTML5 origin (scheme + hostname + non-standard port) and <code>localStorage</code> being an instance of <code>Storage</code> as opposed to <code>globalStorage[location.hostname]</code> being an instance of <code>StorageObsolete</code> which is covered below. For example, <a class="external" href="http://example.com" rel="freelink">http://example.com</a> is not able to access the same <code>localStorage</code> object as <a class="link-https" href="https://example.com" rel="freelink">https://example.com</a> but they can access the same <code>globalStorage</code> item. <code>localStorage</code> is a standard interface while <code>globalStorage</code> is non-standard so you shouldn't rely on these.</p>

<p>Please note that setting a property on <code>globalStorage[location.hostname]</code> does <strong>not</strong> set it on <code>localStorage</code> and extending <code>Storage.prototype</code> does not affect <code>globalStorage</code> items; only extending <code>StorageObsolete.prototype</code> does.</p>

<h4 id="Storage_format">Storage format</h4>

<p><code>Storage</code> keys and values are both stored in the UTF-16 <a href="/en-US/docs/Web/API/DOMString">DOMString</a> format, which uses 2 bytes per character.</p>

<p> </p>