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

PBJS Core: clean side-effect when checking that local storage is enabled #6323

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
9 changes: 7 additions & 2 deletions src/storageManager.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { hook } from './hook.js';
import {hook} from './hook.js';
import * as utils from './utils.js';
import includes from 'core-js-pure/features/array/includes.js';

Expand Down Expand Up @@ -110,7 +110,12 @@ export function newStorageManager({gvlid, moduleName, moduleType} = {}) {
try {
localStorage.setItem('prebid.cookieTest', '1');
return localStorage.getItem('prebid.cookieTest') === '1';
} catch (error) {}
} catch (error) {
} finally {
try {
localStorage.removeItem('prebid.cookieTest');
} catch (error) {}
}
}
return false;
}
Expand Down
29 changes: 27 additions & 2 deletions test/spec/unit/core/storageManager_spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -46,16 +46,17 @@ describe('storage manager', function() {

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

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

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

Expand All @@ -70,4 +71,28 @@ describe('storage manager', function() {
sinon.assert.calledThrice(errorLogSpy);
})
})

describe('localstorage is enabled', function() {
let localStorage;

beforeEach(function() {
localStorage = window.localStorage;
localStorage.clear();
});

afterEach(function() {
localStorage.clear();
})

it('should remove side-effect after checking', function () {
const storage = getStorageManager();

localStorage.setItem('unrelated', 'dummy');
const val = storage.localStorageIsEnabled();

expect(val).to.be.true;
expect(localStorage.length).to.be.eq(1);
expect(localStorage.getItem('unrelated')).to.be.eq('dummy');
});
});
});