cros-data
Version:
cross domian localstorage
2 lines (1 loc) • 2.87 kB
JavaScript
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e=e||self).crosData=t()}(this,(function(){"use strict";return{Client:function(){function e(e){var t=this;this.parent=window,this.origin=new URL(e).origin,this.sendQueue=[],this.messageId=0,this.cbs={},this.child=null,this.createIframe(e),window.addEventListener("message",(function(e){if("string"==typeof e.data&&""!==e.data){var s=JSON.parse(e.data);s.status?e.origin===t.origin&&(t.cbs[s.messageId].reslove(s.data),delete t.cbs[s.messageId]):(t.cbs[s.messageId].reject(s.error),delete t.cbs[s.messageId])}}))}return e.prototype.createIframe=function(e){var t=this,s=document.createElement("iframe");s.style.cssText="width:1px;height:1px;border:0;position:absolute;left:-9999px;top:-9999px;",s.setAttribute("src",e),document.body.appendChild(s),s.onload=function(){t.child=s.contentWindow,t.sendQueue.forEach((function(e){return e()}))}},e.prototype.postHanle=function(e,t,s){var i=this,a={messageId:this.messageId,action:e,origin:new URL(location.href).origin,data:t?{key:t,val:s}:void 0};return this.child?this.child.postMessage(JSON.stringify(a),this.origin):this.sendQueue.push((function(){i.child.postMessage(JSON.stringify(a),i.origin)})),new Promise((function(e,t){i.cbs[i.messageId]={reslove:e,reject:t},i.messageId++}))},e.prototype.set=function(e,t){return this.postHanle("set",e,t)},e.prototype.get=function(e,t){return this.postHanle("get",e,t)},e.prototype.del=function(e,t){return this.postHanle("del",e,t)},e.prototype.clear=function(){return this.postHanle("clear")},e}(),Hub:function(){function e(e){var t=this;this.Permissions=[],this.Permissions=e,window.addEventListener("message",(function(e){if("string"==typeof e.data&&""!==e.data){var s=JSON.parse(e.data);if(s.origin===e.origin){s.data;var i=s.action;if(t.permitted(s)){a=t[i].apply(t,[s]);window.top.postMessage(JSON.stringify(a),e.origin)}else{var a={messageId:s.messageId,data:{},status:!1,error:"没有权限"};window.top.postMessage(JSON.stringify(a),e.origin)}}}}))}return e.prototype.permitted=function(e){for(var t=0;t<this.Permissions.length;t++){var s=this.Permissions[t];if(s.origin.test(e.origin))return s.allow.indexOf(e.action)>-1}return!1},e.prototype.set=function(e){var t;return window.localStorage.setItem(e.data.key,e.data.val),{messageId:e.messageId,data:(t={},t[e.data.key]=e.data.val,t),status:!0}},e.prototype.get=function(e){var t;return window.localStorage.getItem(e.data.key),{messageId:e.messageId,data:(t={},t[e.data.key]=e.data.val,t),status:!0}},e.prototype.del=function(e){var t;return window.localStorage.removeItem(e.data.key),{messageId:e.messageId,data:(t={},t[e.data.key]=e.data.val,t),status:!0}},e.prototype.clear=function(e){return window.localStorage.clear(),{messageId:e.messageId,status:!0}},e}(),_VERSION:"1.0.3"}}));