Merge "objectcache: Use faster getArrayCopy() in WAN cache methods"
[lhc/web/wiklou.git] / resources / src / mediawiki / mediawiki.storage.js
1 ( function ( mw ) {
2 'use strict';
3
4 // Catch exceptions to avoid fatal in Chrome's "Block data storage" mode
5 // which throws when accessing the localStorage property itself, as opposed
6 // to the standard behaviour of throwing on getItem/setItem. (T148998)
7 var
8 localStorage = ( function () {
9 try {
10 return window.localStorage;
11 } catch ( e ) {}
12 }() ),
13 sessionStorage = ( function () {
14 try {
15 return window.sessionStorage;
16 } catch ( e ) {}
17 }() );
18
19 /**
20 * A wrapper for an HTML5 Storage interface (`localStorage` or `sessionStorage`)
21 * that is safe to call on all browsers.
22 *
23 * @class mw.SafeStorage
24 * @private
25 * @param {Object|undefined} store The Storage instance to wrap around
26 */
27 function SafeStorage( store ) {
28 this.store = store;
29 }
30
31 /**
32 * Retrieve value from device storage.
33 *
34 * @param {string} key Key of item to retrieve
35 * @return {string|boolean} False when localStorage not available, otherwise string
36 */
37 SafeStorage.prototype.get = function ( key ) {
38 try {
39 return this.store.getItem( key );
40 } catch ( e ) {}
41 return false;
42 };
43
44 /**
45 * Set a value in device storage.
46 *
47 * @param {string} key Key name to store under
48 * @param {string} value Value to be stored
49 * @return {boolean} Whether the save succeeded or not
50 */
51 SafeStorage.prototype.set = function ( key, value ) {
52 try {
53 this.store.setItem( key, value );
54 return true;
55 } catch ( e ) {}
56 return false;
57 };
58
59 /**
60 * Remove a value from device storage.
61 *
62 * @param {string} key Key of item to remove
63 * @return {boolean} Whether the save succeeded or not
64 */
65 SafeStorage.prototype.remove = function ( key ) {
66 try {
67 this.store.removeItem( key );
68 return true;
69 } catch ( e ) {}
70 return false;
71 };
72
73 /**
74 * A wrapper for the HTML5 `localStorage` interface
75 * that is safe to call on all browsers.
76 *
77 * @class
78 * @singleton
79 * @extends mw.SafeStorage
80 */
81 mw.storage = new SafeStorage( localStorage );
82
83 /**
84 * A wrapper for the HTML5 `sessionStorage` interface
85 * that is safe to call on all browsers.
86 *
87 * @class
88 * @singleton
89 * @extends mw.SafeStorage
90 */
91 mw.storage.session = new SafeStorage( sessionStorage );
92
93 }( mediaWiki ) );