Cross-Domain Post-Messaging

8.0.32 · active · verified Tue Apr 21

post-robot is a JavaScript library that simplifies secure cross-domain communication between browser windows (e.g., parent/iframe, opener/popup) using the native HTML5 `postMessage` API. It provides a robust, promise-based listener/sender pattern, abstracting away the complexities of serialization and asynchronous communication. A key differentiator is its ability to automatically serialize and deserialize complex data types, including functions, Promises (wrapped in `ZalgoPromise`), and Error objects, enabling advanced inter-window interactions. The library ensures reliable messaging with built-in error handling, timeouts, and options for securing channels by specifying target windows or domains. The current stable version is 8.0.32, and while a strict release cadence isn't explicitly stated, it is actively maintained by KrakenJS. This library is crucial for applications requiring seamless interaction between different origins.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates setting up a `post-robot` listener in one window and sending a message to it from another window. It showcases passing data, handling asynchronous responses with Promises, and even invoking functions that were returned across the domain boundary. It includes basic error handling for timeouts.

import postRobot from 'post-robot';

// --- Listener Window (e.g., in an iframe) ---
postRobot.on('getUserDetails', function(event) {
    const userId = event.data.id;
    console.log(`Listener received request for user ID: ${userId} from ${event.origin}`);

    // Simulate fetching user data asynchronously
    return new Promise(resolve => {
        setTimeout(() => {
            if (userId === 123) {
                resolve({
                    id: userId,
                    name: 'Alice Smith',
                    email: 'alice@example.com',
                    // Functions can also be returned and invoked remotely
                    logStatus: (status) => console.log(`[Remote Log] Alice's status: ${status}`)
                });
            } else {
                resolve(null); // User not found
            }
        }, 500);
    });
});

console.log('post-robot listener initialized for getUserDetails.');

// --- Sender Window (e.g., parent window) ---
// This would typically be in a *different* window context, e.g., the parent window calling the iframe.
// For demonstration, we'll simulate the call.

// In a real scenario, 'someWindow' would be window.frames[0] or a popup window reference.
const someWindow = window.opener || window.parent; // Placeholder, adjust for actual target window

if (someWindow && someWindow !== window) {
    postRobot.send(someWindow, 'getUserDetails', { id: 123 }, { timeout: 3000 })
        .then(function(event) {
            const user = event.data;
            if (user) {
                console.log(`Sender received user: ${user.name} from ${event.origin}`);
                user.logStatus('active'); // Call a function passed from the other window
            } else {
                console.log('Sender: User not found.');
            }
        })
        .catch(function(err) {
            console.error('Sender error:', err.message);
        });
} else {
    console.warn('Sender simulation: Target window not found. This code needs to run in a separate context to function.');
}

view raw JSON →