Commit 66af98c5 authored by Robert Knight's avatar Robert Knight

Convert `localStorage` service to JS

parent 6d9bd921
module.exports = ['$window', ($window) ->
# Detection is needed because we run often as a third party widget and
# third party storage blocking often blocks cookies and local storage
# https://github.com/Modernizr/Modernizr/blob/master/feature-detects/storage/localstorage.js
storage = do ->
key = 'hypothesis.testKey'
try
$window.localStorage.setItem key, key
$window.localStorage.removeItem key
$window.localStorage
catch
memoryStorage = {}
getItem: (key) ->
if key of memoryStorage then memoryStorage[key] else null
setItem: (key, value) ->
memoryStorage[key] = value
removeItem: (key) ->
delete memoryStorage[key]
return {
getItem: (key) ->
storage.getItem key
getObject: (key) ->
json = storage.getItem key
return JSON.parse json if json
null
setItem: (key, value) ->
storage.setItem key, value
setObject: (key, value) ->
repr = JSON.stringify value
storage.setItem key, repr
removeItem: (key) ->
storage.removeItem key
}
]
'use strict';
/**
* Fallback in-memory store if `localStorage` is not read/writable.
*/
class InMemoryStorage {
constructor() {
this._store = {};
}
getItem(key) {
return (key in this._store) ? this._store[key] : null;
}
setItem(key, value) {
this._store[key] = value;
}
removeItem(key) {
delete this._store[key];
}
}
/**
* A wrapper around the `localStorage` API which provides a fallback to
* in-memory storage in browsers that block access to `window.localStorage`.
* in third-party iframes.
*/
// @ngInject
function localStorage($window) {
var storage = $window.localStorage;
try {
// Test whether we can read/write localStorage.
var key = 'hypothesis.testKey';
$window.localStorage.setItem(key, key);
$window.localStorage.getItem(key);
$window.localStorage.removeItem(key);
} catch (e) {
storage = new InMemoryStorage();
}
return {
getItem(key) {
return storage.getItem(key);
},
getObject(key) {
var item = storage.getItem(key);
return item ? JSON.parse(item) : null;
},
setItem(key, value) {
storage.setItem(key, value);
},
setObject(key, value) {
var repr = JSON.stringify(value);
storage.setItem(key, repr);
},
removeItem(key) {
storage.removeItem(key);
},
};
}
module.exports = localStorage;
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment