Electron - Webview
Electron - Modern Webview Usage
Section titled “Electron - Modern Webview Usage”The <webview> tag in Electron allows you to embed ‘guest’ content (like external web pages) directly into your Electron application. This content is isolated within the webview container, running in a separate process. This separation is crucial for security, as it prevents the guest content from having the same permissions as your application’s main web page, protecting your app from potentially malicious embedded content. All interactions between your app and the embedded guest content are asynchronous.
While <webview> is available, it’s important to note that for many use cases, Electron’s BrowserView API offers a more flexible and often preferred way to embed web content with greater control. For simple, sandboxed content, a standard HTML <iframe> with a sandbox attribute can also be an option. However, this tutorial will focus on the <webview> tag as per the original scope.
Let’s illustrate embedding an external webpage using <webview>. We’ll embed the official Electron website. First, create your main.js file:
const { app, BrowserWindow } = require('electron');const path = require('path');
let mainWindow;
function createWindow() { mainWindow = new BrowserWindow({ width: 1000, height: 700, webPreferences: { // webviewTag is true by default, but explicitly setting it is good practice if needed. // webviewTag: true, nodeIntegration: false, // Recommended for security contextIsolation: true // Recommended for security } });
mainWindow.loadFile(path.join(__dirname, 'index.html'));
mainWindow.on('closed', () => { mainWindow = null; });}
app.whenReady().then(createWindow);
app.on('window-all-closed', () => { if (process.platform !== 'darwin') { app.quit(); }});
app.on('activate', () => { if (BrowserWindow.getAllWindows().length === 0) { createWindow(); }});Next, create the index.html file that will host the <webview> tag:
<!DOCTYPE html><html><head> <meta charset="UTF-8"> <title>Electron Webview Example</title> <style> body, html { margin: 0; padding: 0; height: 100%; overflow: hidden; display: flex; flex-direction: column; } .controls { padding: 10px; background-color: #f0f0f0; text-align: center; } #myWebview { flex-grow: 1; /* Takes remaining space */ width: 100%; border: none; } .indicator { font-style: italic; color: #555; } </style></head><body> <div class="controls"> <h2>Embedding Electron's Official Website Below</h2> <div class="indicator"></div> </div> <webview id="myWebview" src="https://www.electronjs.org/" style="height: calc(100vh - 70px); width: 100%;"></webview>
<script> document.addEventListener('DOMContentLoaded', () => { const webview = document.getElementById('myWebview'); const indicator = document.querySelector('.indicator');
const handleLoadStart = () => { indicator.textContent = 'Loading guest content...'; };
const handleLoadStop = () => { indicator.textContent = 'Guest content loaded.'; };
const handleLoadFail = (event) => { indicator.textContent = `Failed to load: ${event.errorCode} ${event.errorDescription}`; console.error('Webview failed to load:', event); };
webview.addEventListener('did-start-loading', handleLoadStart); webview.addEventListener('did-stop-loading', handleLoadStop); webview.addEventListener('did-fail-load', handleLoadFail);
// For more advanced interactions, you might need a preload script for the webview itself // using its 'preload' attribute, e.g., <webview preload="./webview-preload.js" ...> // This allows sandboxed communication between the host page and guest content. }); </script></body></html>To run this application, navigate to your project directory in the terminal and execute:
npx electron .The application window will open, displaying a header and below it, the Electron official website loaded within the webview. A message like ‘Loading guest content…’ will appear initially, changing to ‘Guest content loaded.’ once the site is displayed.
The <webview> tag emits various events (like did-start-loading, did-stop-loading, console-message, etc.) that you can listen to for more granular control and feedback. Refer to the official Electron documentation for a complete list of events and methods available for the <webview> tag.
Using <webview> is particularly recommended when embedding third-party content due to its process isolation, which enhances security. Always ensure you understand the security implications of embedding external content. For finer-grained control over embedded views, consider using BrowserView.