Skip to content

Commit dbc94d8

Browse files
committed
fix(localStorage): parsing safety grevory#230
1 parent 0466c13 commit dbc94d8

File tree

2 files changed

+18
-1
lines changed

2 files changed

+18
-1
lines changed

src/angular-local-storage.js

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -163,7 +163,11 @@ angularLocalStorage.provider('localStorageService', function() {
163163
return null;
164164
}
165165

166-
return JSON.parse(item);
166+
try {
167+
return JSON.parse(item);
168+
} catch (e) {
169+
return item;
170+
}
167171
};
168172

169173
// Remove an item from local storage

test/spec/localStorageSpec.js

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -500,6 +500,19 @@ describe('localStorageService', function() {
500500
});
501501
}));
502502

503+
// Backward compatibility issue-#230
504+
it('should return the item as-is if the parsing fail', inject(function($window, localStorageService) {
505+
var items = ['{', '[', 'foo'];
506+
//set keys
507+
items.forEach(function(item, i) {
508+
$window.localStorage.setItem('ls.' + i, item);
509+
});
510+
511+
items.forEach(function(item, i) {
512+
expect(localStorageService.get(i)).toEqual(item);
513+
});
514+
}));
515+
503516
//sessionStorage
504517
describe('SessionStorage', function() {
505518

0 commit comments

Comments
 (0)