npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

vite-plugin-iframe-communication

v1.8.3-beta.15

Published

Vite plugin for enabling iframe communication with parent windows using MessageChannel

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 -D

Usage

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

  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

Features

  • 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

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 URL

    • url: The current URL of the iframe
  • NAVIGATION_STATE: Sent with navigation capability status

    • canGoBack: Whether back navigation is available
    • canGoForward: Whether forward navigation is available (always false due to browser limitations)
  • CONSOLE_ERROR (when using custom error handling): Forward console errors to parent

    • error: The error message
    • filename: 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 iframe

    • cmd: 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

  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 detection
    • Sends URL changes to the parent
    • Responds to navigation commands from the parent
    • Exposes message port globally as window.__messagePort for custom error handling

Inspect Mode

  1. During the Vite transform phase, the plugin:

    • Parses .tsx and .jsx files using Babel
    • Identifies intrinsic JSX elements (lowercase HTML tags like <div>, <button>, etc.)
    • Injects data-src-file, data-src-line, and data-src-col attributes with source location info
    • Skips custom components (uppercase tags) since they don't render to DOM directly
  2. 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-editor API 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