Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Check localstorage availability before accessing it #5616

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions src/storageManager.js
Original file line number Diff line number Diff line change
Expand Up @@ -154,7 +154,7 @@ export function newStorageManager({gvlid, moduleName, moduleType} = {}) {
*/
const setDataInLocalStorage = function (key, value, done) {
let cb = function (result) {
if (result && result.valid) {
if (result && result.valid && hasLocalStorage()) {
window.localStorage.setItem(key, value);
}
}
Expand All @@ -174,7 +174,7 @@ export function newStorageManager({gvlid, moduleName, moduleType} = {}) {
*/
const getDataFromLocalStorage = function (key, done) {
let cb = function (result) {
if (result && result.valid) {
if (result && result.valid && hasLocalStorage()) {
return window.localStorage.getItem(key);
}
return null;
Expand All @@ -194,7 +194,7 @@ export function newStorageManager({gvlid, moduleName, moduleType} = {}) {
*/
const removeDataFromLocalStorage = function (key, done) {
let cb = function (result) {
if (result && result.valid) {
if (result && result.valid && hasLocalStorage()) {
window.localStorage.removeItem(key);
}
}
Expand Down
27 changes: 27 additions & 0 deletions test/spec/unit/core/storageManager_spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -42,5 +42,32 @@ describe('storage manager', function() {
storage.setCookie('foo1', 'baz1');
expect(deviceAccessSpy.calledOnce).to.equal(true);
deviceAccessSpy.restore();
});

describe('localstorage forbidden access in 3rd-party context', function() {
let errorLogSpy;
const originalLocalStorage = { get: () => window.localStorage };
const localStorageMock = { get: () => { throw Error } };

beforeEach(function() {
Object.defineProperty(window, 'localStorage', localStorageMock);
errorLogSpy = sinon.spy(utils, 'logError');
});

afterEach(function() {
Object.defineProperty(window, 'localStorage', originalLocalStorage);
errorLogSpy.restore();
})

it('should not throw if the localstorage is not accessible when setting/getting/removing from localstorage', function() {
const coreStorage = getStorageManager();

coreStorage.setDataInLocalStorage('key', 'value');
const val = coreStorage.getDataFromLocalStorage('key');
coreStorage.removeDataFromLocalStorage('key');

expect(val).to.be.null;
sinon.assert.calledThrice(errorLogSpy);
})
})
});