What is window-post-message-proxy?
The window-post-message-proxy npm package is designed to facilitate communication between different windows or iframes in a web application using the postMessage API. It provides a simple and consistent interface for sending and receiving messages, handling message events, and managing message listeners.
What are window-post-message-proxy's main functionalities?
Sending Messages
This feature allows you to send messages from one window to another. The `postMessage` method takes the target window, the message object, and the target origin as parameters.
const proxy = new WindowPostMessageProxy();
proxy.postMessage(window, { type: 'greeting', text: 'Hello, world!' }, '*');
Receiving Messages
This feature allows you to set up handlers to receive and process messages. The `addHandler` method takes an object with `test` and `handle` functions. The `test` function determines if the handler should process the message, and the `handle` function processes the message.
const proxy = new WindowPostMessageProxy();
proxy.addHandler({
test: message => message.type === 'greeting',
handle: message => console.log('Received message:', message)
});
Removing Handlers
This feature allows you to remove previously added message handlers. The `removeHandler` method takes the handler object that was added using `addHandler`.
const proxy = new WindowPostMessageProxy();
const handler = {
test: message => message.type === 'greeting',
handle: message => console.log('Received message:', message)
};
proxy.addHandler(handler);
proxy.removeHandler(handler);
Other packages similar to window-post-message-proxy
post-robot
The post-robot package provides a robust and flexible way to handle cross-domain messaging between windows and iframes. It offers features like message validation, request/response patterns, and error handling. Compared to window-post-message-proxy, post-robot has more advanced features and is suitable for more complex messaging scenarios.
penpal
Penpal is a package that simplifies communication between iframes and their parent windows. It focuses on providing a promise-based API for sending and receiving messages, making it easier to work with asynchronous code. Penpal is more focused on ease of use and promises, whereas window-post-message-proxy provides a more traditional event-based approach.
iframe-messenger
iframe-messenger is a lightweight library for sending messages between iframes and their parent windows. It provides a simple API for posting messages and listening for responses. Compared to window-post-message-proxy, iframe-messenger is more minimalistic and may be easier to integrate for simple use cases.
window-post-message-proxy
A library used in place of the native window.postMessage which when used on both the sending and receiving windows allow for a nicer asynchronouse promise messaging between the windows.
When sending messages using the proxy, it will apply a unique id to the message, create a deferred object referenced by the id, and pass the message on to the target window.
The target window will also have an instance of the windowPostMessage proxy setup which will send back messages and preserve the unique id.
Then the original sending instance receives the response messag with id, it will look to see if there is matching id in cache and if so resolve the deferred object with the response.
Installation
npm install --save window-post-message-proxy
Basic Usage
const iframe = document.getElementById("myFrame");
const windowPostMessageProxy = new WindowPostMessageProxy();
const message = {
key: "Value"
};
windowPostMessageProxy.postMessage(iframe.conentWindow, message)
.then(response => {
});
Advanced Customization
Customizing how tracking properties are added to the method
By default the windowPostMessage proxy will store the tracking properties as object on the message by known property: windowPostMesssageProxy
.
This means if you call:
const message = {
key: "Value"
};
windowPostMessageProxy.postMessage(iframe.conentWindow, message);
The message is actually modified before it's sent to become:
{
windowPostMessageProxy: {
id: "ebixvvlbwa3tvtjra4i"
},
key: "Value"
};
If you want to customize how the tracking properties are added to and retreived from the message you can provide it at construction time as an object with two funtions. See the interface below:
export interface IProcessTrackingProperties {
addTrackingProperties<T>(message: T, trackingProperties: ITrackingProperties): T;
getTrackingProperties(message: any): ITrackingProperties;
}
addTrackingProperties
takes a message adds the tracking properties object an returns the message.
getTrackingProperties
takes a message and extracts the tracking properties.
Example:
const customProcessTrackingProperties = {
addTrackingProperties(message, trackingProperties) {
message.headers = {
'tracking-id': trackingProperties.id
};
return message;
},
getTrackingProperties(message): ITrackingProperties {
return {
id: message.headers['tracking-id']
};
}
};
const windowPostMessageProxy = new WindowPostMessageProxy(customProcessTrackingProperties);
Customizing how messages are detected as error responses.
By default response messages are considered error message if they contain an error property.
You can override this behavior by passing an isErrorMessage
function at construction time. See interface:
export interface IIsErrorMessage {
(message: any): boolean;
}
Example:
function isErrorMessage(message: any) {
return !(200 <= message.status && message.status < 300);
}
const windowPostMessageProxy = new WindowPostMessageProxy({ isErrorMessage });
Logging messages
By default messagse are not logged, but you can override this behavior by passing logMessages: true
in the options object.
const windowPostMessageProxy = new WindowPostMessageProxy({ logMessages: true });
This will print out a stringified JSON of each object that is recieved or sent by the specific instance.
Supplying custom name
Each windowPostMessageProxy gives itself a randomly generated name so you can see which instance is communicating in the log messages.
Oftem times you may want to pass a custom name which window the windowPostMessageProxy instance is running.
You can provided a name by passing name: 'Iframe'
in the options object.
const windowPostMessageProxy = new WindowPostMessageProxy({ name: 'Iframe' });
Supress Warning Message about unhandled messages
By default the window post message proxy will warn you if it received a message that was not handled since this is usually an indication of error; however,
if you are register multiple window message handlers the message may handled but it's just not able to be known by the windowPostMessageProxy and this warning no longer applies.
const windowPostMessageProxy = new WindowPostMessageProxy({ suppressMessageNotHandledWarning: true });