How to Implement the Webview Tag for Embedding External Web Content in Electron

Electron's <webview> tag is a custom HTML element that embeds external web content inside an out-of-process iframe (OOPIF), running the guest page in an isolated renderer process while exposing a rich API for navigation, scripting, and IPC communication.

The electron/electron repository provides a powerful <webview> implementation that allows developers to embed external web content directly within desktop applications. When you implement the webview tag for embedding external web content, you gain fine-grained control over guest page navigation, preload scripts, and secure inter-process communication while maintaining process isolation between your host page and embedded content.

Architecture of the Webview Tag Implementation

Electron implements the <webview> tag as a custom element that wraps an out-of-process iframe (OOPIF). When a <webview> node is added to the DOM, Electron creates an internal <iframe> via WebViewImpl.createInternalElement and marks it as a webview via hooks.setIsWebView. This element is then registered with Chromium's guest view machinery through guestViewInternal.createGuest.

The guest view runs in its own renderer process, isolated from the embedder page. All communication—including method calls, property access, and events—is proxied through a bridge that forwards calls to the guestViewInternal module using invoke, invokeSync, propertyGet, and propertySet.

Enabling the Webview Tag in Electron

Before using the tag, you must explicitly enable it in your BrowserWindow configuration. Set webviewTag: true in the webPreferences object; otherwise, the custom element will not be registered and the tag will behave as an unknown HTML element.

Main Process Configuration

// main.js (main process)
const { app, BrowserWindow } = require('electron');

function createWindow () {
  const win = new BrowserWindow({
    width: 1000,
    height: 800,
    webPreferences: {
      // Essential: enable the webview tag
      webviewTag: true,
      // Recommended: enable context isolation for security
      contextIsolation: true,
      preload: `${__dirname}/preload.js`
    }
  });

  win.loadFile('index.html');
}

app.whenReady().then(createWindow);

Implementing the Webview in Renderer Process

Once enabled, you can use the <webview> tag in your HTML. The element supports numerous attributes—such as src, preload, nodeintegration, and allowpopups—that are defined in WebViewElement.observedAttributes and handled by WebViewImpl.handleWebviewAttributeMutation.

HTML Markup

<!-- index.html (renderer process) -->
<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title>Webview Demo</title>
    <style>
      webview { 
        width: 100%; 
        height: 100%; 
        display: inline-flex; 
      }
    </style>
  </head>
  <body>
    <webview id="myWebview"
             src="https://example.com"
             preload="./webview-preload.js"
             nodeintegration
             allowpopups
             style="display:inline-flex; width:100%; height:100%;">
    </webview>

    <script src="renderer.js"></script>
  </body>
</html>

Guest Preload Scripts

You can inject a preload script that runs in the guest context before any other scripts. This script has access to ipcRenderer to communicate with the embedder.

// webview-preload.js (runs inside the guest context)
const { ipcRenderer } = require('electron');

window.addEventListener('DOMContentLoaded', () => {
  // Notify the embedder that the guest is ready
  ipcRenderer.sendToHost('guest-ready');
});

// Listen for messages from the embedder
ipcRenderer.on('set-dark-mode', (_, enabled) => {
  document.body.classList.toggle('dark', enabled);
});

Communicating Between Embedder and Guest Content

The setupMethods function in web-view-impl.ts installs thin wrappers for synchronous methods (goBack, goForward), asynchronous methods (executeJavaScript), and properties (src, title). These wrappers call guestViewInternal.invoke, invokeSync, or propertyGet/propertySet to proxy the request to the guest process.

Events originating from the guest are dispatched via WebViewImpl.dispatchEvent, which creates a native Event and re-emits it on the <webview> node in the embedder.

// renderer.js (embedder side)
window.addEventListener('DOMContentLoaded', () => {
  const webview = document.getElementById('myWebview');

  // Listen for navigation events
  webview.addEventListener('did-start-loading', () => console.log('Loading…'));
  webview.addEventListener('did-finish-load', () => console.log('Finished loading'));

  // Call navigation methods
  document.getElementById('backBtn').onclick = () => webview.goBack();
  document.getElementById('forwardBtn').onclick = () => webview.goForward();

  // Execute JavaScript in the guest context
  document.getElementById('getTitleBtn').onclick = async () => {
    const title = await webview.executeJavaScript('document.title');
    console.log('Guest title:', title);
  };

  // Handle IPC messages from guest preload script
  webview.addEventListener('ipc-message', (event) => {
    if (event.channel === 'guest-ready') {
      console.log('Guest reported ready');
      // Send message back to guest
      webview.send('set-dark-mode', true);
    }
  });
});

Key Source Files and Implementation Details

Understanding the internal structure helps debug complex embedding scenarios. The implementation spans several key files in the electron/electron repository:

File Role
lib/renderer/web-view/web-view-element.ts Defines the custom element via setupWebView, registers observedAttributes, and implements lifecycle callbacks (connectedCallback, disconnectedCallback, attributeChangedCallback)
lib/renderer/web-view/web-view-impl.ts Contains WebViewImpl class with createInternalElement (iframe creation), createGuest (guest registration), setupMethods (API proxying), and dispatchEvent (event forwarding)
lib/renderer/web-view/web-view-attributes.ts Implements attribute objects that parse and validate values (e.g., src, partition, preload) before updating the guest
lib/renderer/web-view/web-view-constants.ts Defines constant strings for attribute names and error messages
docs/api/webview-tag.md Official API documentation listing all attributes, methods, and events
spec/webview-spec.ts Test suite verifying navigation, events, and method behavior
patches/chromium/webview_fullscreen.patch Chromium-level patch enabling fullscreen support for webview guests

Summary

  • Enable the tag by setting webviewTag: true in your BrowserWindow's webPreferences before you can use the element.
  • Process isolation is enforced by default; the guest runs in a separate renderer process via Chromium's guest view machinery, protecting your host page from crashes or security issues in embedded content.
  • API surface is implemented in lib/renderer/web-view/web-view-impl.ts, where methods like goBack() and executeJavaScript() are proxied to the guest process via guestViewInternal.invoke.
  • Lifecycle management occurs through standard custom element callbacks (connectedCallback, disconnectedCallback) defined in lib/renderer/web-view/web-view-element.ts, ensuring proper guest registration and cleanup.
  • Communication between embedder and guest relies on IPC via ipcRenderer.sendToHost in preload scripts and the ipc-message event on the webview element.

Frequently Asked Questions

Do I need to enable context isolation to use the webview tag?

No, context isolation is not strictly required, but it is strongly recommended for security. The webview implementation in lib/renderer/web-view/web-view-element.ts registers the custom element in the main world via setupWebView, allowing it to function correctly even when contextIsolation is enabled in your BrowserWindow configuration.

How do I send messages from the guest page back to the embedder?

Use ipcRenderer.sendToHost inside the guest's preload script. The embedder listens for the ipc-message event on the webview element. This bridge is established through the dispatchEvent method in lib/renderer/web-view/web-view-impl.ts, which re-emits guest events as standard DOM events on the webview node.

Can I execute JavaScript in the guest context from the host page?

Yes, call webview.executeJavaScript(code, userGesture) which returns a Promise resolving to the result. This method is proxied through guestViewInternal.invoke as defined in the setupMethods function within lib/renderer/web-view/web-view-impl.ts, allowing safe cross-process script execution.

Why is my webview element not displaying any content?

First, verify that webviewTag: true is explicitly set in the webPreferences of your BrowserWindow. Second, ensure the webview has explicit dimensions via CSS (width, height, or display properties), as the internal iframe created by WebViewImpl.createInternalElement requires layout space to render. Finally, check that the src attribute points to a valid URL and that CSP restrictions aren't blocking the load.

Have a question about this repo?

These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:

Share the following with your agent to get started:
curl -s "https://instagit.com/install.md"

Works with
Claude Codex Cursor VS Code OpenClaw Any MCP Client

Maintain an open-source project? Get it listed too →