Skip to content

Commit bd45a28

Browse files
committed
Merge pull request #126 from jsg2021/make-localstorage-env-node-safe
Make localstorage env node safe
2 parents ee3f98e + ffc34fa commit bd45a28

File tree

1 file changed

+18
-7
lines changed

1 file changed

+18
-7
lines changed

Diff for: lib/environment/LocalStorageKeyEnvironment.js

+18-7
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
"use strict";
1+
'use strict';
22

33
var Environment = require('./Environment');
44

@@ -7,31 +7,42 @@ var Environment = require('./Environment');
77
*/
88
function LocalStorageKeyEnvironment(key) {
99
this.key = key;
10-
this.onStorage = this.onStorage.bind(this);
10+
var store = this.onStorage = this.onStorage.bind(this);
11+
12+
this.storage = (typeof window !== 'undefined' && window.localStorage) || {
13+
data: {},
14+
getItem: function(key) {return this.data[key];},
15+
setItem: function(key, val) {this.data[key]=val;store();}
16+
};
17+
1118
Environment.call(this);
1219
}
1320

1421
LocalStorageKeyEnvironment.prototype = Object.create(Environment.prototype);
1522
LocalStorageKeyEnvironment.prototype.constructor = LocalStorageKeyEnvironment;
1623

1724
LocalStorageKeyEnvironment.prototype.getPath = function() {
18-
return window.localStorage.getItem(this.key) || '';
25+
return this.storage.getItem(this.key) || '';
1926
};
2027

2128
LocalStorageKeyEnvironment.prototype.pushState = function(path, navigation) {
22-
window.localStorage.setItem(this.key, path);
29+
this.storage.setItem(this.key, path);
2330
};
2431

2532
LocalStorageKeyEnvironment.prototype.replaceState = function(path, navigation) {
26-
window.localStorage.setItem(this.key, path);
33+
this.storage.setItem(this.key, path);
2734
};
2835

2936
LocalStorageKeyEnvironment.prototype.start = function() {
30-
window.addEventListener('storage', this.onStorage, false);
37+
if (typeof window !== 'undefined' && window.addEventListener) {
38+
window.addEventListener('storage', this.onStorage, false);
39+
}
3140
};
3241

3342
LocalStorageKeyEnvironment.prototype.stop = function() {
34-
window.removeEventListener('storage', this.onStorage);
43+
if (typeof window !== 'undefined' && window.removeEventListener) {
44+
window.removeEventListener('storage', this.onStorage);
45+
}
3546
};
3647

3748
LocalStorageKeyEnvironment.prototype.onStorage = function() {

0 commit comments

Comments
 (0)