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)
8 localStorage
= ( function () {
10 return window
.localStorage
;
13 sessionStorage
= ( function () {
15 return window
.sessionStorage
;
20 * A wrapper for an HTML5 Storage interface (`localStorage` or `sessionStorage`)
21 * that is safe to call on all browsers.
23 * @class mw.SafeStorage
25 * @param {Object|undefined} store The Storage instance to wrap around
27 function SafeStorage( store
) {
32 * Retrieve value from device storage.
34 * @param {string} key Key of item to retrieve
35 * @return {string|null|boolean} String value, null if no value exists, or false
36 * if storage is not available.
38 SafeStorage
.prototype.get = function ( key
) {
40 return this.store
.getItem( key
);
46 * Set a value in device storage.
48 * @param {string} key Key name to store under
49 * @param {string} value Value to be stored
50 * @return {boolean} The value was set
52 SafeStorage
.prototype.set = function ( key
, value
) {
54 this.store
.setItem( key
, value
);
61 * Remove a value from device storage.
63 * @param {string} key Key of item to remove
64 * @return {boolean} Whether the key was removed
66 SafeStorage
.prototype.remove = function ( key
) {
68 this.store
.removeItem( key
);
75 * Retrieve JSON object from device storage.
77 * @param {string} key Key of item to retrieve
78 * @return {Object|null|boolean} Object, null if no value exists or value
79 * is not JSON-parseable, or false if storage is not available.
81 SafeStorage
.prototype.getObject = function ( key
) {
82 var json
= this.get( key
);
84 if ( json
=== false ) {
89 return JSON
.parse( json
);
96 * Set an object value in device storage by JSON encoding
98 * @param {string} key Key name to store under
99 * @param {Object} value Object value to be stored
100 * @return {boolean} The value was set
102 SafeStorage
.prototype.setObject = function ( key
, value
) {
105 json
= JSON
.stringify( value
);
106 return this.set( key
, json
);
112 * A wrapper for the HTML5 `localStorage` interface
113 * that is safe to call on all browsers.
117 * @extends mw.SafeStorage
119 mw
.storage
= new SafeStorage( localStorage
);
122 * A wrapper for the HTML5 `sessionStorage` interface
123 * that is safe to call on all browsers.
127 * @extends mw.SafeStorage
129 mw
.storage
.session
= new SafeStorage( sessionStorage
);