/** * 支持回调的seeionStorage库 */ const webSessionStorage = { preId: 'hikauto-', status: { SUCCESS: 0, FAILURE: 1, OVERFLOW: 2, }, storage: sessionStorage || window.sessionStorage, getKey: function (key: string) { return this.preId + key; }, set: function ( key: string, value: string | number, cb?: (status: number, key: string, value: string | number) => void, ) { let _status = this.status.SUCCESS; const _key = this.getKey(key); try { this.storage.setItem(_key, value + ''); } catch (e) { _status = this.status.OVERFLOW; } cb && cb.call(this, _status, _key, value); }, get: function ( key: string, cb?: (status: number, value: string | number | null) => void, ) { const _key = this.getKey(key), that = this; let status = this.status.SUCCESS, value = null, result; try { value = that.storage.getItem(_key); } catch (e) { result = { status: that.status.FAILURE, value: null, }; cb && cb.call(this, result.status, result.value); return result; } if (!value) { status = that.status.FAILURE; } result = { status: status, value: value, }; cb && cb.call(this, result.status, result.value); return result; }, // 删除storage,如果删除成功,返回删除的内容 remove: function ( key: string, cb?: (status: number, value: string | number | null) => void, ) { const _key = this.getKey(key); let status = this.status.FAILURE, value; try { value = this.storage.getItem(_key); } catch (e) { // dosomething } if (value) { try { this.storage.removeItem(_key); status = this.status.SUCCESS; } catch (e) { // dosomething } } cb && cb.call(this, status, status > 0 ? null : value + ''); }, }; export default webSessionStorage;