Skip to content

Commit 6053eb4

Browse files
authored
Merge pull request #217 from abdmmar/abdmmar-branch
LocalStorage, sessionStorage
2 parents 54f81c1 + 7332fb4 commit 6053eb4

File tree

1 file changed

+100
-103
lines changed

1 file changed

+100
-103
lines changed
+100-103
Original file line numberDiff line numberDiff line change
@@ -1,83 +1,82 @@
11
# LocalStorage, sessionStorage
22

3-
Web storage objects `localStorage` and `sessionStorage` allow to save key/value pairs in the browser.
3+
Objek penyimpanan web `localStorage` dan `sessionStorage` memungkinkan untuk menyimpan pasangan *key*/*value* di peramban.
44

5-
What's interesting about them is that the data survives a page refresh (for `sessionStorage`) and even a full browser restart (for `localStorage`). We'll see that very soon.
5+
Yang menarik dari mereka adalah bahwa data bertahan dari refresh halaman (untuk `sessionStorage`) dan bahkan ketika peramban dimulai ulang secara penuh (untuk `localStorage`). Kita akan melihatnya segera.
66

7-
We already have cookies. Why additional objects?
7+
Kita sudah memiliki cookies. Mengapa perlu tambahan objek?
88

9-
- Unlike cookies, web storage objects are not sent to server with each request. Because of that, we can store much more. Most browsers allow at least 2 megabytes of data (or more) and have settings to configure that.
10-
- Also unlike cookies, the server can't manipulate storage objects via HTTP headers. Everything's done in JavaScript.
11-
- The storage is bound to the origin (domain/protocol/port triplet). That is, different protocols or subdomains infer different storage objects, they can't access data from each other.
9+
- Tidak seperti cookies, objek penyimpanan web tidak dikirim ke server pada setiap permintaan. Karena itu, kita bisa menyimpan lebih banyak. Sebagian besar peramban mengizinkan setidaknya 2 *megabyte* data (atau lebih) dan memiliki pengaturan untuk konfigurasinya.
10+
- Juga tidak seperti cookies, server tidak dapat memanipulasi objek penyimpanan melalui HTTP header. Semuanya dilakukan dalam JavaScript.
11+
- Penyimpanan terikat kepada asalnya (domain/protokol/port triplet). Artinya, protokol atau subdomain yang berbeda menyimpulkan objek penyimpanan yang berbeda, mereka tidak dapat mengakses data satu sama lain.
1212

13-
Both storage objects provide same methods and properties:
13+
Kedua objek penyimpanan menyediakan *method* dan properti yang sama:
1414

15-
- `setItem(key, value)` -- store key/value pair.
16-
- `getItem(key)` -- get the value by key.
17-
- `removeItem(key)` -- remove the key with its value.
18-
- `clear()` -- delete everything.
19-
- `key(index)` -- get the key on a given position.
20-
- `length` -- the number of stored items.
15+
- `setItem(key, value)` -- menyimpan pasangan *key*/*value*.
16+
- `getItem(key)` -- mendapatkan *value* dengan sebuah *key*.
17+
- `removeItem(key)` -- menghapus *key* beserta *value*-nya.
18+
- `clear()` -- menghapus semuanya.
19+
- `key(index)` -- mendapatkan *key* pada posisi tertentu.
20+
- `length` -- jumlah item yang disimpan.
2121

22-
As you can see, it's like a `Map` collection (`setItem/getItem/removeItem`), but also allows access by index with `key(index)`.
22+
Seperti yang Anda lihat, ini seperti koleksi `Map` (`setItem/getItem/removeItem`), tetapi juga memungkinkan akses berdasarkan indeks dengan `key(index)`.
2323

24-
Let's see how it works.
24+
Mari kita lihat cara kerjanya.
2525

26-
## localStorage demo
26+
## Demo localStorage
2727

28-
The main features of `localStorage` are:
28+
Fitur utama `localStorage` adalah:
2929

30-
- Shared between all tabs and windows from the same origin.
31-
- The data does not expire. It remains after the browser restart and even OS reboot.
30+
- Dibagikan antara semua *tab* dan *window* dari *origin* yang sama.
31+
- Data tidak kedaluwarsa. Data tetap tersimpan setelah peramban *restart* dan bahkan setelah OS *reboot*.
3232

33-
For instance, if you run this code...
33+
Misalnya, jika Anda menjalankan kode ini...
3434

3535
```js run
3636
localStorage.setItem('test', 1);
3737
```
3838

39-
...And close/open the browser or just open the same page in a different window, then you can get it like this:
39+
...Dan kemudian menutup/membuka peramban atau hanya membuka halaman yang sama di jendela yang berbeda, maka Anda bisa mendapatkannya seperti ini:
4040

4141
```js run
4242
alert( localStorage.getItem('test') ); // 1
4343
```
4444

45-
We only have to be on the same origin (domain/port/protocol), the url path can be different.
45+
Kita hanya harus berada di *origin* yang sama (domain/port/protocol), *path* urlnya bisa berbeda.
4646

47-
The `localStorage` is shared between all windows with the same origin, so if we set the data in one window, the change becomes visible in another one.
47+
`localStorage` dibagi antara semua *window* dengan *origin* yang sama, jadi jika kita mengatur data di satu *window*, perubahan akan terlihat di *window* lain.
4848

49-
## Object-like access
49+
## Akses seperti objek
5050

51-
We can also use a plain object way of getting/setting keys, like this:
51+
Kita juga dapat menggunakan cara sebuah objek biasa untuk mendapatkan/mengatur *key*, seperti ini:
5252

5353
```js run
54-
// set key
54+
// mengatur key
5555
localStorage.test = 2;
5656

57-
// get key
57+
// mendapatkan key
5858
alert( localStorage.test ); // 2
5959

60-
// remove key
60+
// menghapus key
6161
delete localStorage.test;
6262
```
6363

64-
That's allowed for historical reasons, and mostly works, but generally not recommended, because:
64+
Itu diizinkan karena alasan historis, dan sebagian besar berfungsi, tetapi umumnya tidak disarankan, karena:
6565

66-
1. If the key is user-generated, it can be anything, like `length` or `toString`, or another built-in method of `localStorage`. In that case `getItem/setItem` work fine, while object-like access fails:
66+
1. Jika *key* dibuat oleh pengguna, itu bisa apa saja, seperti `length` atau `toString`, atau *method* bawaan `localStorage` lainnya. Dalam hal itu `getItem/setItem` berfungsi dengan baik, sementara akses seperti objek akan gagal:
6767
```js run
6868
let key = 'length';
6969
localStorage[key] = 5; // Error, can't assign length
7070
```
71+
2. Ada *event* `storage`, yang dipicu saat kita mengubah data. *Event* itu tidak terjadi untuk akses seperti objek. Kita akan melihatnya nanti di bab ini.
7172

72-
2. There's a `storage` event, it triggers when we modify the data. That event does not happen for object-like access. We'll see that later in this chapter.
73+
## Pengulangan pada keys
7374

74-
## Looping over keys
75+
Seperti yang telah kita lihat, *method* menyediakan fungsionalitas "mendapatkan/mengatur/menghapus dengan *key*". Tetapi bagaimana cara mendapatkan semua *value* atau *key* yang disimpan?
7576

76-
As we've seen, the methods provide "get/set/remove by key" functionality. But how to get all saved values or keys?
77+
Sayangnya, objek penyimpanan tidak bisa dilakukan iterasi.
7778

78-
Unfortunately, storage objects are not iterable.
79-
80-
One way is to loop over them as over an array:
79+
Salah satu caranya adalah dengan mengulangnya sebagai senarai (array):
8180

8281
```js run
8382
for(let i=0; i<localStorage.length; i++) {
@@ -86,29 +85,28 @@ for(let i=0; i<localStorage.length; i++) {
8685
}
8786
```
8887

89-
Another way is to use `for key in localStorage` loop, just as we do with regular objects.
88+
Cara lain adalah dengan menggunakan perulangan `for key in localStorage`, seperti yang kita lakukan dengan objek reguler.
9089

91-
It iterates over keys, but also outputs few built-in fields that we don't need:
90+
Ini melakukan iterasi pada *key*, tetapi juga menampilkan beberapa *field* bawaan yang tidak kita perlukan:
9291

9392
```js run
94-
// bad try
93+
// Percobaan yang buruk
9594
for(let key in localStorage) {
96-
alert(key); // shows getItem, setItem and other built-in stuff
95+
alert(key); // menampilkan getItem, setItem and hal bawaan lainnya
9796
}
9897
```
9998

100-
...So we need either to filter fields from the prototype with `hasOwnProperty` check:
101-
99+
...Jadi kita perlu memfilter *field* dari *prototype* dengan pemeriksaan `hasOwnProperty`:
102100
```js run
103101
for(let key in localStorage) {
104102
if (!localStorage.hasOwnProperty(key)) {
105-
continue; // skip keys like "setItem", "getItem" etc
103+
continue; // melewati keys seperti "setItem", "getItem" etc
106104
}
107105
alert(`${key}: ${localStorage.getItem(key)}`);
108106
}
109107
```
110108

111-
...Or just get the "own" keys with `Object.keys` and then loop over them if needed:
109+
...Atau jika hanya mendapatkan *key*-nya saja dengan `Object.keys` dan kemudian dilakukan perulangan jika diperlukan:
112110

113111
```js run
114112
let keys = Object.keys(localStorage);
@@ -117,133 +115,132 @@ for(let key of keys) {
117115
}
118116
```
119117

120-
The latter works, because `Object.keys` only returns the keys that belong to the object, ignoring the prototype.
121-
118+
Yang terakhir berfungsi, karena `Object.keys` hanya mengembalikan kunci milik objek, mengabaikan *prototype*.
122119

123-
## Strings only
120+
## Hanya string
124121

125-
Please note that both key and value must be strings.
122+
Harap dicatat bahwa *key* dan *value* harus berupa string.
126123

127-
If were any other type, like a number, or an object, it gets converted to string automatically:
124+
Jika ada tipe lain, seperti angka, atau objek, itu akan dikonversi menjadi string secara otomatis:
128125

129126
```js run
130127
localStorage.user = {name: "John"};
131128
alert(localStorage.user); // [object Object]
132129
```
133130

134-
We can use `JSON` to store objects though:
131+
Kita dapat menggunakan `JSON` untuk menyimpan objek:
135132

136133
```js run
137134
localStorage.user = JSON.stringify({name: "John"});
138135
139-
// sometime later
136+
// kemudian
140137
let user = JSON.parse( localStorage.user );
141138
alert( user.name ); // John
142139
```
143140

144-
Also it is possible to stringify the whole storage object, e.g. for debugging purposes:
141+
Juga dimungkinkan untuk *stringify* seluruh objek penyimpanan, sebagai contoh untuk tujuan *debugging*:
145142

146143
```js run
147-
// added formatting options to JSON.stringify to make the object look nicer
144+
// menambahkan opsi pemformatan pada JSON.stringify untuk membuat objek terlihat lebih bagus
148145
alert( JSON.stringify(localStorage, null, 2) );
149146
```
150147

151148

152149
## sessionStorage
153150

154-
The `sessionStorage` object is used much less often than `localStorage`.
151+
Objek `sessionStorage` lebih jarang digunakan daripada `localStorage`.
155152

156-
Properties and methods are the same, but it's much more limited:
153+
Properti dan *method*-nya sama, tetapi jauh lebih terbatas:
157154

158-
- The `sessionStorage` exists only within the current browser tab.
159-
- Another tab with the same page will have a different storage.
160-
- But it is shared between iframes in the same tab (assuming they come from the same origin).
161-
- The data survives page refresh, but not closing/opening the tab.
155+
- `sessionStorage` hanya ada di dalam tab peramban saat ini.
156+
- Tab lain dengan halaman yang sama akan memiliki penyimpanan yang berbeda.
157+
- Tapi dibagi antar iframe di tab yang sama (dengan asumsi mereka berasal dari *origin* yang sama).
158+
- Data bertahan dari *refresh* halaman, tetapi tidak dengan menutup/membuka tab.
162159

163-
Let's see that in action.
160+
Mari kita lihat langsung prakteknya.
164161

165-
Run this code...
162+
Jalankan kode ini...
166163

167164
```js run
168165
sessionStorage.setItem('test', 1);
169166
```
170167

171-
...Then refresh the page. Now you can still get the data:
168+
...Kemudian *refresh* halaman. Sekarang Anda masih bisa mendapatkan data:
172169

173170
```js run
174-
alert( sessionStorage.getItem('test') ); // after refresh: 1
171+
alert( sessionStorage.getItem('test') ); // setelah refresh: 1
175172
```
176173

177-
...But if you open the same page in another tab, and try again there, the code above returns `null`, meaning "nothing found".
174+
...Tetapi jika Anda membuka halaman yang sama di tab lain, dan mencoba lagi di sana, kode di atas mengembalikan `null`, yang berarti "tidak ada yang ditemukan".
178175

179-
That's exactly because `sessionStorage` is bound not only to the origin, but also to the browser tab. For that reason, `sessionStorage` is used sparingly.
176+
Itu persis terjadi karena `sessionStorage` terikat tidak hanya pada *origin*, tetapi juga pada tab peramban. Oleh karena itu, `sessionStorage` jarang digunakan
180177

181-
## Storage event
178+
## Event storage
182179

183-
When the data gets updated in `localStorage` or `sessionStorage`, [storage](https://www.w3.org/TR/webstorage/#the-storage-event) event triggers, with properties:
180+
Saat data diperbarui di `localStorage` atau `sessionStorage`, *event* [storage](https://www.w3.org/TR/webstorage/#the-storage-event) terpicu, dengan properti:
184181

185-
- `key` – the key that was changed (`null` if `.clear()` is called).
186-
- `oldValue` – the old value (`null` if the key is newly added).
187-
- `newValue` – the new value (`null` if the key is removed).
188-
- `url` – the url of the document where the update happened.
189-
- `storageArea` – either `localStorage` or `sessionStorage` object where the update happened.
182+
- `key`*key* yang diubah (`null` jika `.clear()` dipanggil).
183+
- `oldValue`*value* lama (`null` jika *key* baru ditambahkan).
184+
- `newValue`*value* baru (`null` jika key dihapus).
185+
- `url` – url dokumen tempat pembaruan terjadi.
186+
- `storageArea`objek `localStorage` atau `sessionStorage` tempat pembaruan terjadi.
190187

191-
The important thing is: the event triggers on all `window` objects where the storage is accessible, except the one that caused it.
188+
Yang penting adalah: *event* terpicu pada semua objek `window` tempat penyimpanan dapat diakses, kecuali yang menyebabkannya.
192189

193-
Let's elaborate.
190+
Mari kita perjelas.
194191

195-
Imagine, you have two windows with the same site in each. So `localStorage` is shared between them.
192+
Bayangkan, Anda memiliki dua *window* dengan situs yang sama di masing-masing *window*. Jadi `localStorage` dibagi di antara keduanya.
196193

197194
```online
198-
You might want to open this page in two browser windows to test the code below.
195+
Anda mungkin ingin membuka halaman ini di dua window peramban untuk menguji kode di bawah ini.
199196
```
200197

201-
If both windows are listening for `window.onstorage`, then each one will react on updates that happened in the other one.
198+
Jika kedua *window* mendengarkan (listening) `window.onstorage`, maka masing-masing akan bereaksi terhadap pembaruan yang terjadi di *window* lainnya.
202199

203200
```js run
204-
// triggers on updates made to the same storage from other documents
205-
window.onstorage = event => { // same as window.addEventListener('storage', event => {
201+
// memicu pembaruan yang dibuat ke penyimpanan yang sama dari dokumen lain
202+
window.onstorage = event => { //sama seperti window.addEventListener('storage', event => {
206203
if (event.key != 'now') return;
207204
alert(event.key + ':' + event.newValue + " at " + event.url);
208205
};
209206
210207
localStorage.setItem('now', Date.now());
211208
```
212209

213-
Please note that the event also contains: `event.url` -- the url of the document where the data was updated.
210+
Harap perhatikan bahwa *event* juga berisi: `event.url` -- url dokumen tempat data diperbarui.
214211

215-
Also, `event.storageArea` contains the storage object -- the event is the same for both `sessionStorage` and `localStorage`, so `event.storageArea` references the one that was modified. We may even want to set something back in it, to "respond" to a change.
212+
Selain itu, `event.storageArea` berisi objek penyimpanan -- *event*-nya sama untuk `sessionStorage` dan `localStorage`, jadi `event.storageArea` merujuk ke yang telah dimodifikasi. Kita bahkan mungkin ingin mengatur sesuatu kembali di dalamnya, untuk "merespons" perubahan.
216213

217-
**That allows different windows from the same origin to exchange messages.**
214+
**Itu memungkinkan window yang berbeda dari origin yang sama untuk bertukar pesan.**
218215

219-
Modern browsers also support [Broadcast channel API](mdn:/api/Broadcast_Channel_API), the special API for same-origin inter-window communication, it's more full featured, but less supported. There are libraries that polyfill that API, based on `localStorage`, that make it available everywhere.
216+
Peramban modern juga mendukung [Broadcast channel API](mdn:/api/Broadcast_Channel_API), API khusus untuk komunikasi antar-jendela dengan origin yang sama, fiturnya lebih lengkap, tetapi kurang didukung. Ada *libraries* yang melakukan polifill API tersebut, berdasarkan `localStorage`, yang membuatnya tersedia di mana saja.
220217

221-
## Summary
218+
## Ringkasan
222219

223-
Web storage objects `localStorage` and `sessionStorage` allow to store key/value in the browser.
224-
- Both `key` and `value` must be strings.
225-
- The limit is 5mb+, depends on the browser.
226-
- They do not expire.
227-
- The data is bound to the origin (domain/port/protocol).
220+
Objek penyimpanan web `localStorage` dan `sessionStorage` memungkinkan untuk menyimpan *key*/*value* di peramban.
221+
- Baik `key` dan `value` harus berupa string.
222+
- Batasnya adalah 5mb+, tergantung pada peramban.
223+
- Mereka tidak kedaluwarsa.
224+
- Data terikat pada *origin* (domain/port/protokol).
228225
229226
| `localStorage` | `sessionStorage` |
230227
|----------------|------------------|
231-
| Shared between all tabs and windows with the same origin | Visible within a browser tab, including iframes from the same origin |
232-
| Survives browser restart | Survives page refresh (but not tab close) |
228+
| Dibagikan antara semua tab dan window dengan origin yang sama | Terlihat dalam tab browser, termasuk iframe dari origin yang sama |
229+
| Bertahan dari restart peramban | Bertahan dari refresh halaman (tetapi tidak dengan menutup tab) |
233230
234231
API:
235232
236-
- `setItem(key, value)` -- store key/value pair.
237-
- `getItem(key)` -- get the value by key.
238-
- `removeItem(key)` -- remove the key with its value.
239-
- `clear()` -- delete everything.
240-
- `key(index)` -- get the key number `index`.
241-
- `length` -- the number of stored items.
242-
- Use `Object.keys` to get all keys.
243-
- We access keys as object properties, in that case `storage` event isn't triggered.
233+
- `setItem(key, value)` -- menyimpan pasangan *key*/*value*.
234+
- `getItem(key)` -- mendapatkan *value* dengan *key*.
235+
- `removeItem(key)` -- menghapus *key* beserta *value*-nya.
236+
- `clear()` -- menghapus semuanya.
237+
- `key(index)` -- mendapatkan nomor *key* `index`.
238+
- `length` -- jumlah item yang disimpan.
239+
- Gunakan `Object.keys` untuk mendapatkan semua *key*.
240+
- Kita mengakses *key* sebagai properti objek, dalam hal ini *event* `storage` tidak dipicu.
244241

245-
Storage event:
242+
*Event storage*:
246243

247-
- Triggers on `setItem`, `removeItem`, `clear` calls.
248-
- Contains all the data about the operation (`key/oldValue/newValue`), the document `url` and the storage object `storageArea`.
249-
- Triggers on all `window` objects that have access to the storage except the one that generated it (within a tab for `sessionStorage`, globally for `localStorage`).
244+
- Pemicu pada panggilan `setItem`, `removeItem`, `clear`.
245+
- Berisi semua data tentang operasi (`key/oldValue/newValue`), dokumen `url` dan objek penyimpanan `storageArea`.
246+
- Memicu semua objek `window` yang memiliki akses ke penyimpanan kecuali yang membuatnya (dalam tab untuk `sessionStorage`, secara global untuk `localStorage`).

0 commit comments

Comments
 (0)