UNPKG

vuex-multi-tab-state

Version:

Share and synchronize status between multiple tabs with this plugin for Vuex.

3 lines (2 loc) 2.31 kB
!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e(require("dot-object")):"function"==typeof define&&define.amd?define(["dot-object"],e):(t=t||self).vuexMultiTabState=e(t.dotObject)}(this,function(t){function e(){return(e=Object.assign||function(t){for(var e=1;e<arguments.length;e++){var n=arguments[e];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(t[r]=n[r])}return t}).apply(this,arguments)}var n=function(){function t(t){this.tabId=Math.random().toString(36).substring(2,15)+Math.random().toString(36).substring(2,15),this.window=t}var e=t.prototype;return e.storageAvailable=function(){var t="vuex-multi-tab-state-test";try{return this.window.localStorage.setItem(t,t),this.window.localStorage.removeItem(t),!0}catch(t){return!1}},e.saveState=function(t,e){var n=JSON.stringify({id:this.tabId,state:e});this.window.localStorage.setItem(t,n)},e.fetchState=function(t,e){var n=this.window.localStorage.getItem(t);if(n)try{e(JSON.parse(n).state)}catch(e){console.warn("State saved in localStorage with key "+t+" is invalid!")}},e.addEventListener=function(t,e){var n=this;return this.window.addEventListener("storage",function(r){if(r.newValue&&r.key===t)try{var a=JSON.parse(r.newValue);a.id!==n.tabId&&e(a.state)}catch(e){console.warn("New state saved in localStorage with key "+t+" is invalid")}})},t}();return function(r){var a=new n(window),o="vuex-multi-tab",i=[],c=function(t){return t},s=function(t){return t};if(r&&(o=r.key?r.key:o,i=r.statesPaths?r.statesPaths:i,c=r.onBeforeReplace||c,s=r.onBeforeSave||s),!a.storageAvailable())throw new Error("Local storage is not available!");function u(n,r){var a=c(r);a&&n.replaceState(function(n,r){if(0===i.length)return e({},r);var a=function t(e){return Array.isArray(e)?e.map(function(e){return t(e)}):"object"==typeof e&&null!==e?Object.keys(e).reduce(function(n,r){return n[r]=t(e[r]),n},{}):e}(n);return i.forEach(function(e){var n=t.pick(e,r);void 0===n?t.remove(e,a):t.set(e,n,a)}),a}(n.state,a))}return function(e){a.fetchState(o,function(t){u(e,t)}),a.addEventListener(o,function(t){u(e,t)}),e.subscribe(function(e,n){var r=n;i.length>0&&(r=function(e){var n={};return i.forEach(function(r){t.set(r,t.pick(r,e),n)}),n}(n)),(r=s(r))&&a.saveState(o,r)})}}}); //# sourceMappingURL=index.umd.js.map