HTTP Post Message
raw JSON →The `http-post-message` package provides a generic messaging component to facilitate HTTP-style communication over the `window.postMessage` API. It abstracts the raw `postMessage` mechanics into familiar HTTP methods like `get`, `post`, `put`, `patch`, and `delete`, allowing developers to send structured requests and receive responses with HTTP semantics (e.g., status codes, headers). The current stable version is `0.3.0`. It does not implement the underlying `postMessage` transport itself but requires an external implementation of an `IPostMessage` interface, most commonly fulfilled by the `window-post-message-proxy` library, which Microsoft also maintains. Its key differentiator is bringing a robust, HTTP-like request/response pattern to cross-window and cross-iframe communication, simplifying complex messaging scenarios.
Common errors
error TypeError: Cannot read properties of undefined (reading 'postMessage') ↓
IPostMessage interface (e.g., an instance of WindowPostMessageProxy) is passed as the first argument to the HttpPostMessage constructor. error Promise never resolves for http-post-message request. ↓
window-post-message-proxy on both sending and receiving sides uses HttpPostMessage.addTrackingProperties and HttpPostMessage.getTrackingProperties in its processTrackingProperties configuration. error Error: Request failed with status code 500 (or other HTTP error code), but the underlying message was not an error. ↓
window-post-message-proxy is configured with isErrorMessage: HttpPostMessage.isErrorMessage during its instantiation to properly classify incoming messages as errors based on HTTP semantics. Warnings
gotcha This package solely provides the HTTP-style abstraction layer and does NOT implement the actual `window.postMessage` transport. It critically depends on an external library (like `window-post-message-proxy`) to handle the sending and receiving of messages. ↓
breaking The package is still in a `0.x.x` version range. This implies that the API might not be stable and could introduce breaking changes in minor versions without adhering to strict semver for major API shifts. ↓
gotcha Correct configuration of `window-post-message-proxy` is essential for `http-post-message` to interpret responses correctly. Specifically, `processTrackingProperties` and `isErrorMessage` callbacks must be set using `HttpPostMessage`'s static methods. ↓
Install
npm install http-post-message yarn add http-post-message pnpm add http-post-message Imports
- HttpPostMessage wrong
const HttpPostMessage = require('http-post-message').HttpPostMessage;correctimport { HttpPostMessage } from 'http-post-message'; - IPostMessage
import type { IPostMessage } from 'http-post-message'; - HttpPostMessage.addTrackingProperties wrong
import { addTrackingProperties } from 'http-post-message';correctimport { HttpPostMessage } from 'http-post-message'; // ... then use HttpPostMessage.addTrackingProperties
Quickstart
import { HttpPostMessage } from 'http-post-message';
import { WindowPostMessageProxy } from 'window-post-message-proxy';
// 1. Set up a mock postMessage proxy (for demonstration)
// In a real app, you would use WindowPostMessageProxy configured correctly.
const stubPostMessageProxy = {
postMessage: (message: any, targetOrigin?: string, targetWindow?: Window) => {
console.log('Sending message:', message);
// Simulate receiving a response after a delay
return Promise.resolve({
id: message.id, // Important for correlation
data: { status: 200, body: `Echo: ${JSON.stringify(message.data)}` },
error: null
});
},
};
// 2. Instantiate HttpPostMessage with the proxy
const httpPostMessage = new HttpPostMessage(stubPostMessageProxy);
// 3. Make an HTTP-style GET request
async function runExample() {
try {
console.log('Making GET request to target/path...');
const response = await httpPostMessage.get('target/path', { headers: { 'X-Custom-Header': 'value' } });
console.log('Received response:', response.body);
// 4. Make an HTTP-style POST request
console.log('\nMaking POST request to /api/data...');
const postResponse = await httpPostMessage.post('/api/data', { item: 'new item' });
console.log('Received POST response:', postResponse.body);
} catch (error) {
console.error('Request failed:', error);
}
}
runExample();
/* Example output (simplified):
Sending message: { id: '...', url: 'target/path', method: 'GET', data: {}, headers: { 'X-Custom-Header': 'value' } }
Received response: Echo: {}
Making POST request to /api/data...
Sending message: { id: '...', url: '/api/data', method: 'POST', data: { item: 'new item' }, headers: {} }
Received POST response: Echo: {"item":"new item"}
*/