Vite plugin for enabling iframe communication with parent windows using MessageChannel
npm install vite-plugin-iframe-communicationA Vite plugin that enables secure communication between an iframe and its parent window using the MessageChannel API. Perfect for development environments where you need to control iframe navigation from a parent application.
- 🔒 Secure communication using MessageChannel API
- 🧭 Full navigation control (back, forward, refresh, goto)
- 📍 Real-time URL tracking with enhanced detection
- 🎯 Single-page application support
- 🚨 Error handling support (console errors can be forwarded to parent)
- 🛠️ Development-only by default (configurable)
- 🐛 Debug mode for troubleshooting
- 🔍 NEW: Inspect Mode - Click-to-source functionality for JSX elements
- 📝 NEW: Source metadata injection (file, line, column) for debugging
- ⌨️ NEW: Keyboard shortcut to toggle inspect mode
``bash`
npm install vite-plugin-iframe-communication --save-devor
yarn add vite-plugin-iframe-communication -Dor
pnpm add vite-plugin-iframe-communication -D
Add the plugin to your vite.config.ts:
`typescript
import { defineConfig } from 'vite';
import iframeCommunicationPlugin from 'vite-plugin-iframe-communication';
export default defineConfig({
plugins: [
iframeCommunicationPlugin()
]
});
`
`typescript
import { defineConfig } from 'vite';
import iframeCommunicationPlugin from 'vite-plugin-iframe-communication';
export default defineConfig({
plugins: [
iframeCommunicationPlugin({
// Enable debug logging
debug: true,
// Include in production builds (not recommended)
includeInProduction: false,
// Enable inspect mode (click-to-source)
enableInspectMode: true,
// Keyboard shortcut to toggle inspect mode
inspectModeShortcut: 'Alt+Shift+I',
// Use a custom script instead of the default
customScript: ''
})
]
});
`
In your parent application, establish communication with the iframe:
`javascript
const iframe = document.getElementById('your-iframe');
const channel = new MessageChannel();
// Set up message handler
channel.port1.onmessage = (e) => {
const { type, url, canGoBack, canGoForward } = e.data || {};
if (type === 'URL_CHANGED') {
console.log('Iframe navigated to:', url);
updateUrlBar(url);
}
if (type === 'NAVIGATION_STATE') {
updateNavigationButtons(canGoBack, canGoForward);
}
};
// Send handshake when iframe loads
iframe.addEventListener('load', () => {
const targetOrigin = new URL(iframe.src).origin;
iframe.contentWindow.postMessage(
{ type: 'HANDSHAKE' },
targetOrigin,
[channel.port2]
);
});
// Send commands to the iframe
function sendCommand(cmd, payload) {
channel.port1.postMessage({ type: 'CMD', cmd, payload });
}
// Navigation controls
document.getElementById('back-btn').onclick = () => sendCommand('back');
document.getElementById('forward-btn').onclick = () => sendCommand('forward');
document.getElementById('refresh-btn').onclick = () => sendCommand('refresh');
document.getElementById('goto-btn').onclick = () => {
sendCommand('goto', { url: document.getElementById('url-input').value });
};
`
The plugin includes a powerful inspect mode feature that allows you to click on any element in your app and open the source file in your editor at the exact line where that JSX element is defined.
1. Start your Vite dev server
2. Press Alt+Shift+I (or your configured shortcut) to toggle inspect mode
3. Hover over elements to see which file/line they come from
4. Click on an element to open it in your editor
- Source Metadata Injection: Automatically adds data-src-file, data-src-line, and data-src-col attributes to intrinsic JSX elements (lowercase HTML tags)
- Visual Overlay: Shows a blue highlight on the element you're hovering over
- Tooltip: Displays the filename and line number
- Editor Integration: Uses Vite's built-in editor opener to jump to source
- Development Only: Attributes and overlay only injected in dev mode
- SolidJS/React Compatible: Works with any JSX-based framework
Make sure your editor is configured to work with Vite's /__open-in-editor endpoint. Most modern editors (VS Code, WebStorm, etc.) work out of the box.
| Option | Type | Default | Description |
|--------|------|---------|-------------|
| includeInProduction | boolean | false | Whether to inject the script in production builds |debug
| | boolean | false | Enable debug logging to console |enableInspectMode
| | boolean | true | Enable inspect mode and source metadata injection |inspectModeShortcut
| | string | 'Alt+Shift+I' | Keyboard shortcut to toggle inspect mode |customScript
| | string | undefined | Custom script to inject instead of the default |
#### From Iframe to Parent
- URL_CHANGED: Sent when the iframe navigates to a new URLurl
- : The current URL of the iframeNAVIGATION_STATE
- : Sent with navigation capability statuscanGoBack
- : Whether back navigation is availablecanGoForward
- : Whether forward navigation is available (always false due to browser limitations)
- CONSOLE_ERROR (when using custom error handling): Forward console errors to parenterror
- : The error messagefilename
- : Source file of the error (optional)lineno
- : Line number of the error (optional)colno
- : Column number of the error (optional)
#### From Parent to Iframe
- HANDSHAKE: Initial message to establish communication
- Must include MessagePort in the transfer list
- CMD: Command message to control iframecmd
- : The command to execute ('back', 'forward', 'refresh', 'goto')payload
- : Additional data for the command (e.g., { url: '/path' } for goto)
1. The plugin injects a script into your HTML pages during development
2. The script checks if it's running in an iframe
3. It listens for a handshake message from the parent window
4. Once connected, it:
- Tracks all navigation events (pushState, replaceState, popstate, link clicks)
- Intercepts window.location.href changes for better navigation detectionwindow.__messagePort
- Sends URL changes to the parent
- Responds to navigation commands from the parent
- Exposes message port globally as for custom error handling
1. During the Vite transform phase, the plugin:
- Parses .tsx and .jsx files using Babel
- Identifies intrinsic JSX elements (lowercase HTML tags like
,