UNPKG

rx-postmessenger

Version:

Minimal RxJS adapter for the window.postMessage API for request-response streams and notification streams across frame windows.

45 lines (44 loc) 2 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.MessageValidator = void 0; var MessageValidator = /** @class */ (function () { function MessageValidator(acceptedSource, acceptedOrigin) { this.acceptedSource = acceptedSource; this.acceptedOrigin = acceptedOrigin; } /** * Validates the identity of the message's sender and the format of the message's data. * * Checks whether the remoteOrigin location matches any allowed origins. * Separate assertion of the remoteOrigin allows for cross-domain navigation * within this.frame, and still treating inbound messages from the * frame as being equal. * * Checks whether the source Window object equals the remoteWindow object. * This check allows for implementation of multiple i-frames that share the * same remoteOrigin, and still being able to distinguish between messages from * such frames. */ MessageValidator.prototype.validate = function (message) { return message instanceof MessageEvent && message.origin === this.acceptedOrigin && message.source === this.acceptedSource && this.isWellFormedMessage(message.data); }; /** * Tests whether the data sent through postMessage is a well-formed message * object. This serves as runtime data format validation. If messages do not * comply to the AnyMessage compound interface, the entire event is ignored. * * @param {*} message * @return {boolean} */ MessageValidator.prototype.isWellFormedMessage = function (message) { return (typeof message.id === 'string') && (['request', 'response', 'notification'].indexOf(message.type) >= 0) && (typeof message.channel === 'string') && (message.type !== 'response' || (typeof message.requestId === 'string')); }; return MessageValidator; }()); exports.MessageValidator = MessageValidator;