vite-plugin-iframe-communication
v1.8.3-beta.15
Published
Vite plugin for enabling iframe communication with parent windows using MessageChannel
Maintainers
Readme
vite-plugin-iframe-communication
A 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.
Features
- 🔒 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
Installation
npm install vite-plugin-iframe-communication --save-dev
# or
yarn add vite-plugin-iframe-communication -D
# or
pnpm add vite-plugin-iframe-communication -DUsage
Basic Setup
Add the plugin to your vite.config.ts:
import { defineConfig } from 'vite';
import iframeCommunicationPlugin from 'vite-plugin-iframe-communication';
export default defineConfig({
plugins: [
iframeCommunicationPlugin()
]
});With Options
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: '<script>/* your custom script */</script>'
})
]
});Parent Window Integration
In your parent application, establish communication with the iframe:
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 });
};Inspect Mode (Click-to-Source)
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.
How to Use
- Start your Vite dev server
- Press
Alt+Shift+I(or your configured shortcut) to toggle inspect mode - Hover over elements to see which file/line they come from
- Click on an element to open it in your editor
Features
- Source Metadata Injection: Automatically adds
data-src-file,data-src-line, anddata-src-colattributes 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
Requirements
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.
API
Plugin Options
| 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 |
Message Types
From Iframe to Parent
URL_CHANGED: Sent when the iframe navigates to a new URLurl: The current URL of the iframe
NAVIGATION_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)
How It Works
Iframe Communication
- The plugin injects a script into your HTML pages during development
- The script checks if it's running in an iframe
- It listens for a handshake message from the parent window
- Once connected, it:
- Tracks all navigation events (pushState, replaceState, popstate, link clicks)
- Intercepts
window.location.hrefchanges for better navigation detection - Sends URL changes to the parent
- Responds to navigation commands from the parent
- Exposes message port globally as
window.__messagePortfor custom error handling
Inspect Mode
During the Vite transform phase, the plugin:
- Parses
.tsxand.jsxfiles using Babel - Identifies intrinsic JSX elements (lowercase HTML tags like
<div>,<button>, etc.) - Injects
data-src-file,data-src-line, anddata-src-colattributes with source location info - Skips custom components (uppercase tags) since they don't render to DOM directly
- Parses
In the browser (dev mode only):
- A dev overlay script listens for the keyboard shortcut
- When inspect mode is active, it tracks mouse movement
- Highlights elements with source metadata on hover
- Shows a tooltip with file:line:col information
- On click, calls Vite's
/__open-in-editorAPI to open the file in your editor
Security Considerations
- The plugin uses MessageChannel for secure communication
- Origin validation should be implemented in production environments
- The script is not injected in production builds by default
- Always validate URLs before navigation
License
MIT
