diff --git a/lib/createLocalStorage.js b/lib/createLocalStorage.js deleted file mode 100644 index 3b44bd72..00000000 --- a/lib/createLocalStorage.js +++ /dev/null @@ -1,32 +0,0 @@ -import createStore from './helpers/store'; -import { attachOnUnload } from './helpers/dom'; - -/** - * Create the local storage instance and attach the unload handler - * to persist the state. - * @param {Array} keys - * @return {{set, getState, get, reset, remove}} - */ -export default (keys = []) => { - const store = createStore( - keys.reduce((acc, key) => { - return { - ...acc, - [key]: localStorage.getItem(key) - }; - }, {}) - ); - - attachOnUnload(() => { - const data = store.getState(); - keys.forEach((key) => { - const value = data[key]; - if (!value) { - return; - } - window.localStorage.setItem(key, value); - }, {}); - }); - - return store; -}; diff --git a/lib/createSecureSessionStorage.js b/lib/createSecureSessionStorage.js index 7a0330ad..f5832c96 100644 --- a/lib/createSecureSessionStorage.js +++ b/lib/createSecureSessionStorage.js @@ -1,19 +1,32 @@ import createStore from './helpers/store'; import { load, save } from './helpers/secureSessionStorage'; -import { attachOnUnload } from './helpers/dom'; /** - * Create the secure session storage instance and attach the unload handler - * to persist the state. * @param {Array} keys * @return {{set, getState, get, reset, remove}} */ export default (keys = []) => { const store = createStore(load(keys)); - attachOnUnload(() => { - save(keys, store.getState()); - }); + if ('onpagehide' in window) { + const handlePageShow = () => { + // This does not need to do anything. The main purpose is just to reset window.name and sessionStorage to fix the Safari 13.1 described below + load(keys); + }; + + const handlePageHide = () => { + // Cannot use !event.persisted because Safari 13.1 does not send that when you are navigating on the same domain + save(keys, store.getState()); + }; + + window.addEventListener('pageshow', handlePageShow, true); + window.addEventListener('pagehide', handlePageHide, true); + } else { + const handleUnload = () => { + save(keys, store.getState()); + }; + window.addEventListener('unload', handleUnload, true); + } return store; }; diff --git a/lib/helpers/dom.js b/lib/helpers/dom.js index 9ccbbd62..4e7079cc 100644 --- a/lib/helpers/dom.js +++ b/lib/helpers/dom.js @@ -1,15 +1,3 @@ -export const attachOnUnload = (cb) => { - if (window.addEventListener) { - return window.addEventListener('unload', cb, false); - } - - if (window.attachEvent) { - return window.attachEvent('onunload', cb); - } - - throw new Error('No method for adding event listeners!'); -}; - const loadScriptHelper = ({ path, integrity }, cb) => { const script = document.createElement('script');