Commit 60a37459 authored by Randall Leeds's avatar Randall Leeds

Use fallback when local storage throws

In some environments, accessing the "localStorage" property of the
window is enough to throw an error.
parent d451b587
...@@ -28,14 +28,15 @@ class InMemoryStorage { ...@@ -28,14 +28,15 @@ class InMemoryStorage {
*/ */
// @ngInject // @ngInject
function localStorage($window) { function localStorage($window) {
var storage = $window.localStorage; let storage;
let testKey = 'hypothesis.testKey';
try { try {
// Test whether we can read/write localStorage. // Test whether we can read/write localStorage.
var key = 'hypothesis.testKey'; storage = $window.localStorage;
$window.localStorage.setItem(key, key); $window.localStorage.setItem(testKey, testKey);
$window.localStorage.getItem(key); $window.localStorage.getItem(testKey);
$window.localStorage.removeItem(key); $window.localStorage.removeItem(testKey);
} catch (e) { } catch (e) {
storage = new InMemoryStorage(); storage = new InMemoryStorage();
} }
......
'use strict'; 'use strict';
var angular = require('angular'); var angular = require('angular');
var service = require('../local-storage');
describe('sidebar.localStorage', () => { describe('sidebar.localStorage', () => {
var fakeWindow; var fakeWindow;
before(() => before(() =>
angular.module('h', []) angular.module('h', [])
.service('localStorage', require('../local-storage')) .service('localStorage', service)
); );
context('when accessing localStorage throws an Error', () => {
it('returns the fallback implementation', () => {
var badWindow = {};
var fakeWindow = {};
Object.defineProperty(badWindow, 'localStorage', {
get: () => {
throw Error('denied');
},
});
var prototypes = [badWindow, fakeWindow]
.map(service)
.map(Object.getPrototypeOf)
;
assert.strictEqual(prototypes[0], prototypes[1]);
});
});
context('when browser localStorage is *not* accessible', () => { context('when browser localStorage is *not* accessible', () => {
var localStorage = null; var localStorage = null;
var key = null; var key = null;
......
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