@ekolabs/iframily
Advanced tools
Comparing version 0.1.9 to 1.0.0-temp.1
@@ -1,1 +0,1 @@ | ||
!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.Iframily=t():e.Iframily=t()}(this,(function(){return function(e){var t={};function n(i){if(t[i])return t[i].exports;var r=t[i]={i:i,l:!1,exports:{}};return e[i].call(r.exports,r,r.exports,n),r.l=!0,r.exports}return n.m=e,n.c=t,n.d=function(e,t,i){n.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:i})},n.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},n.t=function(e,t){if(1&t&&(e=n(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var i=Object.create(null);if(n.r(i),Object.defineProperty(i,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var r in e)n.d(i,r,function(t){return e[t]}.bind(null,r));return i},n.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return n.d(t,"a",t),t},n.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},n.p="",n(n.s=2)}([function(e,t,n){"use strict";e.exports={PARENT:"parent",CHILD:"child",FRAMILY_ID_PREFIX:"__iframily__",FRAMILY_INIT:"iframily_init",FRAMILY_INIT_SUCCESSFUL:"iframily_init_successful",ATTEMPT_TO_CONNECT_INTERVAL:200}},function(e,t,n){"use strict";function i(e,t){for(var n=0;n<t.length;n++){var i=t[n];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(e,i.key,i)}}var r=n(0),o=["sendMessage","dispose"];e.exports=function(){function e(t,n,i){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),this._id=t,this._onPairedHandler=i.onPairedHandler||function(){},this._onDisposedHandler=i.onDisposedHandler||function(){},this._targetOrigin=i.targetOrigin||"*",this._iframilyUid="".concat(r.FRAMILY_ID_PREFIX).concat(this._id),this._msgHandler=n||function(){},this._hasConnected=!1,this._disposed=!1,this._msgQueue=[],this._pendingCb={},this._cbUid=0,this._bindPublicMethods(),this._init()}var t,n,s;return t=e,(n=[{key:"_bindPublicMethods",value:function(){o.forEach(function(e){this[e]=this[e].bind(this)}.bind(this))}},{key:"_init",value:function(){throw new Error("To be overridden in extending classes.")}},{key:"_sendQueuedMessages",value:function(){this._msgQueue.forEach((function(e){e()})),this._msgQueue=[]}},{key:"_postMessage",value:function(e){try{this._targetWindow.postMessage(e,this._targetOrigin)}catch(e){console.error("[Iframily] - Error when posting message:",e)}}},{key:"_sendMessage",value:function(e,t){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},i={_iframilyUid:this._iframilyUid,_fromType:this._iframilyType,msg:e};t&&(this._cbUid++,this._pendingCb[this._cbUid]=t,i._cbUid=this._cbUid),this._hasConnected||n.forceSend?this._postMessage(i):(console.warn("[Iframily] - No one connected yet, queuing message:",e),this._msgQueue.push(this._postMessage.bind(this,i)))}},{key:"_sendResponse",value:function(e,t){var n={_iframilyUid:this._iframilyUid,_fromType:this._iframilyType,_isResponse:!0,_cbUid:e,_isResolved:t.isResolved,_isRejected:t.isRejected,_cbResolveValue:t.value,_cbRejectError:t.err};this._postMessage(n)}},{key:"_handleMessage",value:function(e){var t=this;e._isResponse?this._handleResponse(e):Promise.resolve().then((function(){return t._msgHandler(e.msg)})).then((function(n){t._sendResponse(e._cbUid,{isResolved:!0,value:n})})).catch((function(n){t._sendResponse(e._cbUid,{isRejected:!0,err:n})}))}},{key:"_handleResponse",value:function(e){if(e._cbUid){var t=this._pendingCb[e._cbUid];if(e._isResolved)t.resolve(e._cbResolveValue);else{if(!e._isRejected)throw new Error("Missing resolve/reject information on response: ".concat(e));t.reject(e._cbRejectError)}delete this._pendingCb[e._cbUid]}}},{key:"_displayDisposedError",value:function(){console.error("[Iframily] - Attempting to use a disposed instance")}},{key:"sendMessage",value:function(e){var t=this;return this._disposed?this._displayDisposedError():new Promise((function(n,i){t._sendMessage(e,{resolve:n,reject:i})}))}},{key:"dispose",value:function(){if(this._disposed)return this._displayDisposedError();this._hasConnected=!1,this._msgQueue=[],this._disposed=!0,this._onDisposedHandler()}},{key:"disposed",get:function(){return this._disposed}},{key:"id",get:function(){return this._id}}])&&i(t.prototype,n),s&&i(t,s),e}()},function(e,t,n){"use strict";function i(e,t){for(var n=0;n<t.length;n++){var i=t[n];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(e,i.key,i)}}var r=n(3),o=n(4),s=n(0),a={},c={};e.exports=function(){function e(){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e)}var t,n,u;return t=e,u=[{key:"initParent",value:function(e,t){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};if(!a[e]||a[e].disposed)return a[e]=new o(e,t,n),a[e];console.error('[Iframily] - A parent iframily with id "'.concat(e,'" was already inited, please use another id or dispose the existing one first.'))}},{key:"initChild",value:function(e,t){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};if(!c[e]||c[e].disposed)return c[e]=new r(e,t,n),c[e];console.error('[Iframily] - A child iframily with id "'.concat(e,'" was already inited, please use another id or dispose the existing one first.'))}},{key:"isIframilyMessage",value:function(e){var t=e&&e.data;return t&&t._iframilyUid&&t._iframilyUid.includes(s.FRAMILY_ID_PREFIX)}}],(n=null)&&i(t.prototype,n),u&&i(t,u),e}()},function(e,t,n){"use strict";function i(e){return(i="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}function r(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function o(e,t){for(var n=0;n<t.length;n++){var i=t[n];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(e,i.key,i)}}function s(e,t,n){return(s="undefined"!=typeof Reflect&&Reflect.get?Reflect.get:function(e,t,n){var i=function(e,t){for(;!Object.prototype.hasOwnProperty.call(e,t)&&null!==(e=f(e)););return e}(e,t);if(i){var r=Object.getOwnPropertyDescriptor(i,t);return r.get?r.get.call(n):r.value}})(e,t,n||e)}function a(e,t){return(a=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e})(e,t)}function c(e){var t=function(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Date.prototype.toString.call(Reflect.construct(Date,[],(function(){}))),!0}catch(e){return!1}}();return function(){var n,i=f(e);if(t){var r=f(this).constructor;n=Reflect.construct(i,arguments,r)}else n=i.apply(this,arguments);return u(this,n)}}function u(e,t){return!t||"object"!==i(t)&&"function"!=typeof t?function(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}(e):t}function f(e){return(f=Object.setPrototypeOf?Object.getPrototypeOf:function(e){return e.__proto__||Object.getPrototypeOf(e)})(e)}var l=n(1),d=n(0);e.exports=function(e){!function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),t&&a(e,t)}(l,e);var t,n,i,u=c(l);function l(){return r(this,l),u.apply(this,arguments)}return t=l,(n=[{key:"_init",value:function(){var e=this;this._iframilyType=d.CHILD,this._targetWindow=window.parent,this._handleMessage=this._handleMessage.bind(this),window.addEventListener("message",this._handleMessage),this._attemptToConnectInterval=setInterval(function t(){return e._sendMessage(d.FRAMILY_INIT,null,{forceSend:!0}),t}(),d.ATTEMPT_TO_CONNECT_INTERVAL)}},{key:"_handleMessage",value:function(e){var t=e&&e.data;t&&t._iframilyUid===this._iframilyUid&&t._fromType===d.PARENT&&(this._hasConnected||t.msg!==d.FRAMILY_INIT_SUCCESSFUL?this._hasConnected&&s(f(l.prototype),"_handleMessage",this).call(this,t):(this._hasConnected=!0,clearInterval(this._attemptToConnectInterval),this._onPairedHandler(),this._sendQueuedMessages()))}},{key:"dispose",value:function(){s(f(l.prototype),"dispose",this).call(this),window.removeEventListener("message",this._handleMessage),clearInterval(this._attemptToConnectInterval)}}])&&o(t.prototype,n),i&&o(t,i),l}(l)},function(e,t,n){"use strict";function i(e){return(i="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}function r(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function o(e,t){for(var n=0;n<t.length;n++){var i=t[n];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(e,i.key,i)}}function s(e,t,n){return(s="undefined"!=typeof Reflect&&Reflect.get?Reflect.get:function(e,t,n){var i=function(e,t){for(;!Object.prototype.hasOwnProperty.call(e,t)&&null!==(e=f(e)););return e}(e,t);if(i){var r=Object.getOwnPropertyDescriptor(i,t);return r.get?r.get.call(n):r.value}})(e,t,n||e)}function a(e,t){return(a=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e})(e,t)}function c(e){var t=function(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Date.prototype.toString.call(Reflect.construct(Date,[],(function(){}))),!0}catch(e){return!1}}();return function(){var n,i=f(e);if(t){var r=f(this).constructor;n=Reflect.construct(i,arguments,r)}else n=i.apply(this,arguments);return u(this,n)}}function u(e,t){return!t||"object"!==i(t)&&"function"!=typeof t?function(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}(e):t}function f(e){return(f=Object.setPrototypeOf?Object.getPrototypeOf:function(e){return e.__proto__||Object.getPrototypeOf(e)})(e)}var l=n(1),d=n(0);e.exports=function(e){!function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),t&&a(e,t)}(l,e);var t,n,i,u=c(l);function l(){return r(this,l),u.apply(this,arguments)}return t=l,(n=[{key:"_init",value:function(){this._iframilyType=d.PARENT,this._handleMessage=this._handleMessage.bind(this),window.addEventListener("message",this._handleMessage)}},{key:"_handleMessage",value:function(e){var t=e&&e.data;if(t&&t._iframilyUid===this._iframilyUid&&t._fromType===d.CHILD)if(t.msg===d.FRAMILY_INIT){if(!this._hasConnected)for(var n=document.getElementsByTagName("iframe"),i=0;i<n.length;i++)if(n[i].contentWindow===e.source){this._targetWindow=n[i].contentWindow,this._hasConnected=!0,this._onPairedHandler(),this._sendMessage(d.FRAMILY_INIT_SUCCESSFUL),this._sendQueuedMessages();break}}else this._hasConnected&&s(f(l.prototype),"_handleMessage",this).call(this,t)}},{key:"dispose",value:function(){s(f(l.prototype),"dispose",this).call(this),window.removeEventListener("message",this._handleMessage)}}])&&o(t.prototype,n),i&&o(t,i),l}(l)}])})); | ||
!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.Iframily=t():e.Iframily=t()}(this,(function(){return function(e){var t={};function n(i){if(t[i])return t[i].exports;var r=t[i]={i:i,l:!1,exports:{}};return e[i].call(r.exports,r,r.exports,n),r.l=!0,r.exports}return n.m=e,n.c=t,n.d=function(e,t,i){n.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:i})},n.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},n.t=function(e,t){if(1&t&&(e=n(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var i=Object.create(null);if(n.r(i),Object.defineProperty(i,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var r in e)n.d(i,r,function(t){return e[t]}.bind(null,r));return i},n.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return n.d(t,"a",t),t},n.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},n.p="",n(n.s=2)}([function(e,t,n){"use strict";e.exports={PARENT:"parent",CHILD:"child",FRAMILY_ID_PREFIX:"__iframily__",FRAMILY_INIT:"iframily_init",FRAMILY_INIT_SUCCESSFUL:"iframily_init_successful",DANGEROUSLY_SET_WILDCARD:"DANGEROUSLY_SET_WILDCARD",ATTEMPT_TO_CONNECT_INTERVAL:200,README_SINGLETON_URL:"https://github.com/EkoLabs/iframily#----iframily-singleton----"}},function(e,t,n){"use strict";function i(e,t){for(var n=0;n<t.length;n++){var i=t[n];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(e,i.key,i)}}var r=n(0),o=["sendMessage","dispose"];e.exports=function(){function e(t,n,i,o){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),this._id=t,this._targetOrigin=n===r.DANGEROUSLY_SET_WILDCARD?"*":n,this._msgHandler=i||function(){},this._onPairedHandler=o.onPairedHandler||function(){},this._onDisposedHandler=o.onDisposedHandler||function(){},this._iframilyUid="".concat(r.FRAMILY_ID_PREFIX).concat(this._id),this._hasConnected=!1,this._isDisposed=!1,this._msgQueue=[],this._pendingCb={},this._cbUid=0,this._bindPublicMethods(),this._init()}var t,n,s;return t=e,(n=[{key:"_bindPublicMethods",value:function(){o.forEach(function(e){this[e]=this[e].bind(this)}.bind(this))}},{key:"_init",value:function(){throw new Error("To be overridden in extending classes.")}},{key:"_sendQueuedMessages",value:function(){this._msgQueue.forEach((function(e){e()})),this._msgQueue=[]}},{key:"_postMessage",value:function(e){try{this._targetWindow.postMessage(e,this._targetOrigin)}catch(e){console.error("[Iframily] - Error when posting message:",e)}}},{key:"_sendMessage",value:function(e,t){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},i={_iframilyUid:this._iframilyUid,_fromType:this._iframilyType,msg:e};t&&(this._cbUid++,this._pendingCb[this._cbUid]=t,i._cbUid=this._cbUid),this._hasConnected||n.forceSend?this._postMessage(i):(console.warn("[Iframily] - No one paired yet, queuing message sent by ".concat(this._iframilyType," id: ").concat(this._id)),this._msgQueue.push(this._postMessage.bind(this,i)))}},{key:"_sendResponse",value:function(e,t){var n={_iframilyUid:this._iframilyUid,_fromType:this._iframilyType,_isResponse:!0,_cbUid:e,_isResolved:t.isResolved,_isRejected:t.isRejected,_cbResolveValue:t.value,_cbRejectError:t.err};this._postMessage(n)}},{key:"_handleMessage",value:function(e){var t=this;e._isResponse?this._handleResponse(e):Promise.resolve().then((function(){return t._msgHandler(e.msg)})).then((function(n){t._sendResponse(e._cbUid,{isResolved:!0,value:n})})).catch((function(n){t._sendResponse(e._cbUid,{isRejected:!0,err:n})}))}},{key:"_handleResponse",value:function(e){if(e._cbUid){var t=this._pendingCb[e._cbUid];if(e._isResolved)t.resolve(e._cbResolveValue);else{if(!e._isRejected)throw new Error("[Iframily] - Missing resolve/reject information on response sent by ".concat(e._fromType," id: ").concat(e._iframilyUid));t.reject(e._cbRejectError)}delete this._pendingCb[e._cbUid]}}},{key:"_displayDisposedError",value:function(){console.error("[Iframily] - Attempting to use a disposed instance")}},{key:"sendMessage",value:function(e){var t=this;return this._isDisposed?this._displayDisposedError():new Promise((function(n,i){t._sendMessage(e,{resolve:n,reject:i})}))}},{key:"dispose",value:function(){if(this._isDisposed)return this._displayDisposedError();this._hasConnected=!1,this._msgQueue=[],this._isDisposed=!0,this._onDisposedHandler()}},{key:"isDisposed",get:function(){return this._isDisposed}},{key:"id",get:function(){return this._id}}])&&i(t.prototype,n),s&&i(t,s),e}()},function(e,t,n){"use strict";function i(e,t){for(var n=0;n<t.length;n++){var i=t[n];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(e,i.key,i)}}function r(e){return(r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}var o=n(3),s=n(4),a=n(0),c={},u={};function f(e,t,n){return!(t[e]&&!t[e].isDisposed)||(console.error("[Iframily] - A ".concat(n,' iframily with id "').concat(e,'" was already initialized, please use another id or dispose the existing one first.')),!1)}function l(e,t){return e?"string"!=typeof e?(console.error('[Iframily] - "targetOrigin" is of type '.concat(r(e),' but must be of type string, not initializing "').concat(t,'" iframily id.')),!1):"*"!==e||(console.error('[Iframily] - "*" (wildcard) is not allowed for "targetOrigin" argument. If you are sure about what you are doing, use "'.concat(a.DANGEROUSLY_SET_WILDCARD,'". See more info here: ').concat(a.README_SINGLETON_URL)),!1):(console.error('[Iframily] - Missing "targetOrigin" argument, not initializing "'.concat(t,'" iframily id.')),!1)}function d(e){return window.parent!==window||(console.error('[Iframily] - Attempted to initialize a child iframily in a non embedded window, not initializing "'.concat(e,'" iframily id.')),!1)}e.exports=function(){function e(){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e)}var t,n,r;return t=e,r=[{key:"initParent",value:function(e,t,n){var i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{};if(f(e,c,"parent")&&l(t,e))return c[e]=new s(e,t,n,i),c[e]}},{key:"initChild",value:function(e,t,n){var i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{};if(f(e,u,"child")&&l(t,e)&&d(e))return u[e]=new o(e,t,n,i),u[e]}},{key:"isIframilyMessage",value:function(e){var t=e&&e.data;return t&&t._iframilyUid&&t._iframilyUid.includes(a.FRAMILY_ID_PREFIX)}}],(n=null)&&i(t.prototype,n),r&&i(t,r),e}()},function(e,t,n){"use strict";function i(e){return(i="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}function r(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function o(e,t){for(var n=0;n<t.length;n++){var i=t[n];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(e,i.key,i)}}function s(e,t,n){return(s="undefined"!=typeof Reflect&&Reflect.get?Reflect.get:function(e,t,n){var i=function(e,t){for(;!Object.prototype.hasOwnProperty.call(e,t)&&null!==(e=f(e)););return e}(e,t);if(i){var r=Object.getOwnPropertyDescriptor(i,t);return r.get?r.get.call(n):r.value}})(e,t,n||e)}function a(e,t){return(a=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e})(e,t)}function c(e){var t=function(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Date.prototype.toString.call(Reflect.construct(Date,[],(function(){}))),!0}catch(e){return!1}}();return function(){var n,i=f(e);if(t){var r=f(this).constructor;n=Reflect.construct(i,arguments,r)}else n=i.apply(this,arguments);return u(this,n)}}function u(e,t){return!t||"object"!==i(t)&&"function"!=typeof t?function(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}(e):t}function f(e){return(f=Object.setPrototypeOf?Object.getPrototypeOf:function(e){return e.__proto__||Object.getPrototypeOf(e)})(e)}var l=n(1),d=n(0);e.exports=function(e){!function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),t&&a(e,t)}(l,e);var t,n,i,u=c(l);function l(){return r(this,l),u.apply(this,arguments)}return t=l,(n=[{key:"_init",value:function(){var e=this;this._iframilyType=d.CHILD,this._targetWindow=window.parent,this._handleMessage=this._handleMessage.bind(this),window.addEventListener("message",this._handleMessage),this._attemptToConnectInterval=setInterval(function t(){return e._sendMessage(d.FRAMILY_INIT,null,{forceSend:!0}),t}(),d.ATTEMPT_TO_CONNECT_INTERVAL)}},{key:"_handleMessage",value:function(e){if("*"===this._targetOrigin||e.origin===this._targetOrigin){var t=e&&e.data;t&&t._iframilyUid===this._iframilyUid&&t._fromType===d.PARENT&&(this._hasConnected||t.msg!==d.FRAMILY_INIT_SUCCESSFUL?this._hasConnected&&s(f(l.prototype),"_handleMessage",this).call(this,t):(this._hasConnected=!0,clearInterval(this._attemptToConnectInterval),this._onPairedHandler(),this._sendQueuedMessages()))}}},{key:"dispose",value:function(){s(f(l.prototype),"dispose",this).call(this),window.removeEventListener("message",this._handleMessage),clearInterval(this._attemptToConnectInterval)}}])&&o(t.prototype,n),i&&o(t,i),l}(l)},function(e,t,n){"use strict";function i(e){return(i="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}function r(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function o(e,t){for(var n=0;n<t.length;n++){var i=t[n];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(e,i.key,i)}}function s(e,t,n){return(s="undefined"!=typeof Reflect&&Reflect.get?Reflect.get:function(e,t,n){var i=function(e,t){for(;!Object.prototype.hasOwnProperty.call(e,t)&&null!==(e=f(e)););return e}(e,t);if(i){var r=Object.getOwnPropertyDescriptor(i,t);return r.get?r.get.call(n):r.value}})(e,t,n||e)}function a(e,t){return(a=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e})(e,t)}function c(e){var t=function(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Date.prototype.toString.call(Reflect.construct(Date,[],(function(){}))),!0}catch(e){return!1}}();return function(){var n,i=f(e);if(t){var r=f(this).constructor;n=Reflect.construct(i,arguments,r)}else n=i.apply(this,arguments);return u(this,n)}}function u(e,t){return!t||"object"!==i(t)&&"function"!=typeof t?function(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}(e):t}function f(e){return(f=Object.setPrototypeOf?Object.getPrototypeOf:function(e){return e.__proto__||Object.getPrototypeOf(e)})(e)}var l=n(1),d=n(0);e.exports=function(e){!function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),t&&a(e,t)}(l,e);var t,n,i,u=c(l);function l(){return r(this,l),u.apply(this,arguments)}return t=l,(n=[{key:"_init",value:function(){this._iframilyType=d.PARENT,this._handleMessage=this._handleMessage.bind(this),window.addEventListener("message",this._handleMessage)}},{key:"_handleMessage",value:function(e){if(("*"===this._targetOrigin||e.origin===this._targetOrigin)&&e.source!==window){var t=e&&e.data;t&&t._iframilyUid===this._iframilyUid&&t._fromType===d.CHILD&&(t.msg===d.FRAMILY_INIT?this._hasConnected||(this._targetWindow=e.source,this._hasConnected=!0,this._onPairedHandler(),this._sendMessage(d.FRAMILY_INIT_SUCCESSFUL),this._sendQueuedMessages()):this._hasConnected&&s(f(l.prototype),"_handleMessage",this).call(this,t))}}},{key:"dispose",value:function(){s(f(l.prototype),"dispose",this).call(this),window.removeEventListener("message",this._handleMessage)}}])&&o(t.prototype,n),i&&o(t,i),l}(l)}])})); |
{ | ||
"name": "@ekolabs/iframily", | ||
"version": "0.1.9", | ||
"description":"Modern iframes communication", | ||
"version": "1.0.0-temp.1", | ||
"description": "postMessage made simple & safe", | ||
"main": "dist/iframily.min.js", | ||
@@ -14,2 +14,3 @@ "license": "Apache-2.0", | ||
"playground": "http-server ./ -c-1 -p 8135 -o /playground/parent.html", | ||
"examples": "http-server ./ -c-1 -p 8136 -o /examples", | ||
"test": "jest", | ||
@@ -16,0 +17,0 @@ "test-debug-mac": "node --inspect-brk node_modules/.bin/jest --runInBand --testTimeout=9999999 --watchAll", |
184
README.md
@@ -1,21 +0,138 @@ | ||
# Iframily | ||
// MY TODO: check readme renders nicely in npm and github (initParent/Child api is longer line...) | ||
// MY TODO: targetOrigin regex not allowed both because it also controls the postMessage() and to avoid "dot" unescaping mistakes | ||
Iframily is a small javascript library that simplifies communication between frames. | ||
// TODO: icon | ||
<img src="https://eko.engineering/static/media/sonorous_logo.83f6c44b.svg" alt="Sonorous" width="200"/> | ||
# Iframily - postMessage made simple & safe | ||
Iframily simplifies working and establishing communication between frames. | ||
It provides a simpler API than [postMessage](https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage), which includes Promise-based responses, message queuing, and holding on to messages until both frames are ready to talk. | ||
This is how it works: | ||
1. Create iframilies in the parent frame. | ||
2. Create iframilies in the child frame. | ||
3. If a parent id and child id match, they will pair. | ||
4. Send messages between paired iframilies. | ||
1. Create iframilies in the parent and child frame. | ||
2. If a parent id and child id match, they will pair. | ||
3. Send messages between paired iframilies. | ||
By the team from [<img src="https://user-images.githubusercontent.com/3951311/86791993-b4c78200-c072-11ea-8936-14db378904a3.png" valign="bottom" width=200 alt="eko Engineering">](https://eko.engineering) | ||
// TODO: decide | ||
**postMessage VS Iframily example:** | ||
```html | ||
<!-- PARENT --> | ||
<iframe src="./child.html" name="myFrame" onload="onIframeLoaded(this)"></iframe> | ||
<script> | ||
window.onIframeLoaded = (iframeEl) => { | ||
window.addEventListener('message', (event) => { | ||
if (event.origin !== 'https://child.domain.com') { | ||
return; | ||
} | ||
if (event.data.callerId === 'someId') { | ||
alert(event.data.msg); | ||
} | ||
}); | ||
let iframeName = iframeEl.getAttribute('name'); | ||
let iframeWindow = window.frames[iframeName]; | ||
iframeWindow.postMessage({ msg: 'Who ya gonna call?', callerId: 'someId' }, 'https://child.domain.com'); | ||
} | ||
</script> | ||
<!-- CHILD --> | ||
<script> | ||
window.addEventListener('message', (event) => { | ||
if (event.origin !== 'https://parent.domain.com') { | ||
return; | ||
} | ||
if (event.data.callerId === 'someId' && event.data.msg === 'hi') { | ||
event.source.postMessage({ msg: 'Ghostbusters! 👻', callerId: 'someId' }); | ||
} | ||
}); | ||
</script> | ||
``` | ||
```html | ||
<!-- PARENT --> | ||
<iframe src="./child.html"></iframe> | ||
<script> | ||
let parentIframily = Iframily.initParent('someId', 'https://child.domain.com'); | ||
parentIframily.sendMessage('Who ya gonna call?').then((response) => { | ||
alert(response); | ||
}); | ||
</script> | ||
<!-- CHILD --> | ||
<script> | ||
Iframily.initChild('someId', 'https://parent.domain.com', (msg) => { | ||
if (msg === 'Who ya gonna call?') { | ||
return 'Ghostbusters! 👻'; | ||
} | ||
}); | ||
</script> | ||
``` | ||
![postMessage vs Iframily example](https://s3.amazonaws.com/storage2.interlude.fm/dev_temp/asaf/iframily/images/post-new.png) | ||
![postMessage vs Iframily example](https://s3.amazonaws.com/storage2.interlude.fm/dev_temp/asaf/iframily/images/iframily-new.png) | ||
## Table of Contents | ||
* [Features]($features) | ||
* [Examples](#examples) | ||
* [Installation](#installation) | ||
* [API](#api) | ||
* [Iframily singleton](#----iframily-singleton----) | ||
* [iframily instance](#----iframily-instance----) | ||
* [Notes](#notes) | ||
* [Contributing](#contributing) | ||
## Features | ||
* Works with cross domain IFrames. | ||
* Send any serializable message. | ||
* Support sync and async responses (Promise based). | ||
* Queue messages sent until pairing has completed. | ||
### What makes it special | ||
## How do I get set up | ||
Iframily pushes you to be more responsible with your frame security by keeping it front and center. You'll need to explicitly specify the allowed origin for communication and the sender's origin for verification, both on the parent and child frames. See more on [initParent() / initChild() API](#----iframily-singleton----). | ||
### What makes it awesome | ||
* Enforces security best practices: Iframily prevents you from accidentally setting too permissive configuration, making you less vulnerable to exploits. | ||
* Long-lived two-way communication between frames. While other libraries treat messages separately, Iframily enables you to easily respond to incoming messages and maintain the communication chain, keeping track of messages and their responses to allow for more complex communications. | ||
* Each frame connection is named and identified, allowing for continuous communication even when a frame redirects or reloads. | ||
* Fast and intuitive promise-based API (supports async responses). | ||
* Discrete handlers can be defined for specific frames or modules in frames, allowing true separation of concerns and code between the different frames and their uses. | ||
* Unlike other libraries, you don’t need to change how you initialize your iframes. Iframily works out of the box with any iframe. Just give it a frame identifier and let it do its thing. | ||
* Message queue until paring completed so messages don’t get lost, even if a frame page hasn’t completed loading yet. | ||
* Zero dependencies. | ||
* Unit + battle tested | ||
// TODO: real codepen links + images | ||
## Examples | ||
[Invasion of the frame snatchers](https://codepen.io/OpherV/pen/xxwRMBw?editors=0100) | ||
Demonstrates a simple usage of Iframily to communicate between a parent and child frame through an interactive, sweet father-son dialogue about world domination. | ||
[<img src="https://user-images.githubusercontent.com/3951311/81201022-71e32280-8fcd-11ea-9b9d-6adcf7fa6394.png" width=400>](https://codepen.io/OpherV/pen/xxwRMBw?editors=0100) | ||
[Text Chat Madness](https://codepen.io/OpherV/pen/PoPQwaz?editors=0010) | ||
Demonstrates usage of Iframily to communicate between a parent frame and multiple child frames through interactive conversations in a family of five. How will mom handle all these questions? You decide! | ||
[<img src="https://user-images.githubusercontent.com/3951311/81200872-3ba5a300-8fcd-11ea-90cf-7de98cacfaf8.png" width=400>](https://codepen.io/OpherV/pen/PoPQwaz?editors=0010) | ||
[Crazy Tetris](https://codepen.io/OpherV/pen/QWjQbmZ?editors=1100) | ||
A novel (and somewhat strange) reimplementation of the classic Tetris using Iframily! Each frame runs its own self-contained Tetris instance. The twist? Instead of moving the pieces, the player moves the frames themselves to align the pieces and allow them to flow freely between frames. | ||
[<img src="https://user-images.githubusercontent.com/3951311/86790421-14249280-c071-11ea-91fd-1fe57bb357e7.png" width=400>](https://codepen.io/OpherV/pen/QWjQbmZ?editors=1100) | ||
See the repo's `examples/` directory for the source code. | ||
## Installation | ||
```shell | ||
@@ -25,6 +142,19 @@ npm i @ekolabs/iframily --save | ||
**ES6** | ||
```javascript | ||
import Iframily from '@ekolabs/iframily'; | ||
``` | ||
**CommonJS** | ||
```javascript | ||
const Iframily = require('@ekolabs/iframily'); | ||
``` | ||
You can also add the library via script tag and use `window.Iframily`, like so: | ||
```html | ||
<!-- latest --> | ||
<script src="https://unpkg.com/@ekolabs/iframily"></script> | ||
<!-- specific version (for example: 1.0.0) --> | ||
<script src="https://unpkg.com/@ekolabs/iframily@1.0.0"></script> | ||
``` | ||
@@ -38,5 +168,5 @@ | ||
#### `Iframily.initParent(id, msgHandler, options) -> iframily instance` | ||
#### `Iframily.initParent(id, targetOrigin, msgHandler, options) -> iframily instance` | ||
#### `Iframily.initChild(id, msgHandler, options) -> iframily instance` | ||
#### `Iframily.initChild(id, targetOrigin, msgHandler, options) -> iframily instance` | ||
@@ -48,7 +178,7 @@ Creates a parent/child [iframily instance](#----iframily-instance----) respectively (to be used in the parent/child frame) and returns it, if successful. | ||
| id | `string` | A unique id to identify this [iframily instance](#----iframily-instance----), this is used in order to match parent and child iframilies. Will abort and log an error if the id already exists in the current frame. | | ||
| msgHandler | `function` | Optional - A handler for incoming messages from the paired iframily in the parent/child frame. The `msgHandler` can return back a response value or a promise that will be resolved/rejected with a response value. | | ||
| targetOrigin | `string` | The URI to use as the target origin for the `postMessage` call and for validating the sender origin on incoming messages, for example: `https://subdomain.domain.com`. For security concerns this argument is mandatory, see [link](https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage) for more info. If both frames our on the same origin, you can use `window.location.origin` as the value. Passing `"*"` (wildcard) is not supported, if you are 100% certain that you want to allow messages to be received and handled by everyone, you can pass `"DANGEROUSLY_SET_WILDCARD"` instead. | | ||
| msgHandler | `function` | Optional - A handler for incoming messages from the paired iframily in the parent/child frame. The `msgHandler` can return back a response value or a promise that will be resolved/rejected with a response value. | | ||
| options | `object` | Optional - Additional options, see possible options below: | | ||
| options.onPairedHandler | `function` | Optional - A handler that will be invoked upon pairing. | | ||
| options.onDisposedHandler | `function` | Optional - A handler that will be invoked when the instance is disposed. | | ||
| options.targetOrigin | `URI` | Optional - The URI to use as the target origin for the `postMessage` call. Use this if you are passing sensitive data, see [link](https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage) for more info. Default is '*'.| | ||
@@ -60,3 +190,3 @@ #### `Iframily.isIframilyMessage(event) -> boolean` | ||
```javascript | ||
window.addEventListener("message", receiveMessage); | ||
window.addEventListener('message', receiveMessage); | ||
@@ -76,3 +206,3 @@ function receiveMessage(event) { | ||
The iframily instance is the object returned when initing a new iframily using the `initParent()` or `initChild()` methods. | ||
The iframily instance is the object returned when initializing a new iframily using the `initParent()` or `initChild()` methods. | ||
@@ -83,5 +213,5 @@ #### `f.sendMessage(msg) -> Promise` | ||
| :-------------: |:--------------:| :------------| | ||
| msg | `serializable` | The message to be sent, can be any serializable (see [structured clone algorithm](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm)). | ||
| msg | `serializable` | The message to be sent, can be any serializable data (see [structured clone algorithm](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm)). | ||
Returns a promise that will be resolved with the response value from the receiving iframily instance message handler. The promise will be rejected if the receiving iframily instance returned a rejected promise. | ||
Returns a promise that will be resolved with the response value from the receiving iframily instance message handler. The promise will be rejected if the promised returned by the receiving iframily instance rejects. | ||
@@ -95,7 +225,7 @@ > if the receiving iframily instance did not return an explicit response value in its message handler, the promise will be resolved with `undefined`. | ||
> * You cannot reuse a disposed instance, you can however create a new instance with the same id. | ||
> * Any iframilies paired with this instance will still keep sending messages to the disposed instance but they will be ignored. | ||
> * Any iframilies paired with this instance will still be able to keep sending messages to the disposed instance but the messages will be ignored by the disposed target. | ||
This method is useful when you have a parent frame which recreates the same child frame and you want to use the same id for the iframilies. | ||
#### `f.disposed -> boolean (read only)` | ||
#### `f.isDisposed -> boolean (read only)` | ||
@@ -106,3 +236,3 @@ Returns `true` if this iframily instance has been disposed. | ||
Returns the id that this iframily was inited with. | ||
Returns the id that this iframily was initialized with. | ||
@@ -121,3 +251,3 @@ ## Usage example | ||
let iframilyParent = Iframily.initParent('myUniqueId', msgHandler); | ||
let iframilyParent = Iframily.initParent('myUniqueId', window.location.origin, msgHandler); | ||
@@ -148,3 +278,5 @@ iframilyParent.sendMessage('do something') | ||
return new Promise((resolve, reject) => { | ||
resolve('OK! done async!'); | ||
setTimeout(() => { | ||
resolve('OK! done async!'); | ||
}, 1000); | ||
}); | ||
@@ -154,3 +286,3 @@ } | ||
let iframilyChild = Iframily.initChild('myUniqueId', msgHandler); | ||
let iframilyChild = Iframily.initChild('myUniqueId', window.location.origin, msgHandler); | ||
@@ -165,3 +297,3 @@ iframilyChild.sendMessage({ text: 'fancy' }); | ||
* You can create multiple iframilies in each frame but the unique ids cannot be used more than once per frame (unless the previous one has been disposed). | ||
* Parent can connect to one child only and vice versa (due to previous note). | ||
* Parent can pair with one child only and vice versa (due to previous note). | ||
* Designed for modern browsers (IE not supported). | ||
@@ -168,0 +300,0 @@ |
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
28551
310