Streamlined iframe communication for modern web applications.
Project details
iframe-link provides a minimalist yet powerful solution for communication between iframes and their parent documents in JavaScript and TypeScript. With Promise-based RPC and efficient event messaging, it simplifies the complexities of postMessage, allowing developers to focus on building robust, interactive web applications without the repetitive overhead of custom implementations.
iframe-link is a minimalist JavaScript and TypeScript library designed to facilitate seamless communication between an iframe and its parent page. By leveraging Promise-based remote procedure calls (RPC) and robust event messaging over window.postMessage, this library simplifies the implementation of bidirectional communication in web applications.
The standard postMessage method lacks a structured approach for handling messages, particularly in terms of request IDs, event routing, and synchronization. iframe-link addresses these gaps by encapsulating the complexities of inter-frame communication. This library minimizes the repetitive setup for each iframe and includes security features, ensuring communication occurs only between trusted origins.
Below are examples demonstrating how to set up iframe-link for both the parent and the iframe:
import { connectToIframe } from 'iframe-link';
type ChildApi = {
getStatus(input: { userId: string }): Promise<{ online: boolean }>
};
const channel = connectToIframe<ChildApi>({
iframe: '#profile-frame',
origin: 'https://child.example.com',
methods: {
getTheme: async () => ({ accent: '#3b82f6' })
}
});
channel.on('STATUS_CHANGED', console.log);
const child = await channel.promise;
await child.getStatus({ userId: '42' });
import { connectToParent } from 'iframe-link';
type ParentApi = {
getTheme(): Promise<{ accent: string }>
};
const channel = connectToParent<ParentApi>({
allowedOrigins: ['https://app.example.com'],
methods: {
getStatus: async ({ userId }) => ({ userId, online: true })
}
});
const parent = await channel.promise;
await parent.getTheme();
channel.emit('STATUS_CHANGED', { online: true });
The following methods are available:
| Member | Purpose |
|---|---|
promise | Resolves to the remote method proxy after the handshake. |
on(type, handler) | Subscribes to an event. |
off(type, handler) | Unsubscribes from an event. |
emit(type, data?) | Emits an event to the other side. |
destroy() | Removes listeners and rejects pending RPC calls. |
iframe-link provides a clean and effective solution for developers seeking to establish reliable iframe communication with minimal overhead. It streamlines interactions between the parent and iframe, supporting complex application scenarios while maintaining an easy-to-use interface.
Comments
0Start the conversation
Share the first comment.