How to Control Web Pages Using the Electron WebContents API
You control web pages in Electron through the webContents property of a BrowserWindow, which exposes methods like loadURL(), executeJavaScript(), and send() to manage navigation, inject code, and handle IPC between the main and renderer processes.
The webContents API is the primary interface in the electron/electron repository for managing web pages from the main process. It acts as a bridge between Chromium's rendering engine and the Node.js environment, allowing developers to programmatically interact with loaded content. Understanding this API is essential for building desktop applications that need to automate browser behavior, communicate with web views, or modify page properties dynamically.
Understanding the WebContents Architecture
Electron renders web pages inside a WebContents object, which wraps Chromium's native content::WebContents and exposes it to JavaScript. The architecture consists of four distinct layers:
- Browser process (C++): The native
content::WebContentsmanages the actual renderer, navigation state, and IPC. Electron wraps this inWebContentsImpllocated inshell/browser/web_contents_impl.handshell/browser/web_contents_impl.cc. - JavaScript API: The public
WebContentsclass inlib/browser/api/web-contents.tsprovides the developer-facing interface (accessed viawin.webContents). - Renderer process: The Blink engine executes JavaScript injected through
executeJavaScriptand receives messages sent from the main process. - UI Container:
BrowserWindoworBrowserViewholds theWebContentsinstance and provides the visual container.
When you call a method like win.webContents.loadURL(), the request flows through this stack: the JavaScript API serializes the request, sends an IPC message to the browser process, and WebContentsImpl invokes the underlying Chromium method.
Core Methods for Controlling Web Pages
Navigation Control
The webContents object provides direct control over page navigation. According to the source code in lib/browser/api/web-contents.ts, key methods include:
loadURL(url[, options]): Loads a resource at the specified URL with optional HTTP headers.reload(): Reloads the current page.goBack()andgoForward(): Navigate through session history if available.stop(): Cancels any pending navigation.canGoBack()/canGoForward(): Check history state before navigating.
JavaScript Execution
To run code inside the page context, use executeJavaScript(code[, userGesture]). This method returns a Promise that resolves with the result of the last expression evaluated in the page. The C++ implementation in shell/browser/web_contents_impl.cc handles the request and marshals the result back to the main process.
Inter-Process Communication
Send asynchronous messages between the main and renderer processes:
send(channel, ...args): Sends a message to the renderer process via the specified channel.ipc-messageevent: Listen for messages sent from the renderer usingipcRenderer.send().
Zoom and Visual Settings
Control page scaling programmatically:
setZoomFactor(factor): Sets the zoom factor (1.0 = 100%, 1.5 = 150%).setZoomLevel(level): Sets the zoom level using Chromium's internal scale.getUserAgent()/setUserAgent(agent): Modify the user agent string for the specific webContents.
Permission Handling
Control access to device features through the session permission handler. While permissions are managed at the session level, they reference the specific webContents instance requesting access, as implemented in shell/browser/web_contents_permission_helper.cc.
Practical Code Examples
Basic Navigation and History Management
const { app, BrowserWindow } = require('electron')
let win
app.whenReady().then(() => {
win = new BrowserWindow({ width: 800, height: 600 })
const wc = win.webContents
// Load a remote page
wc.loadURL('https://www.wikipedia.org')
// Reload after 5 seconds
setTimeout(() => wc.reload(), 5000)
// Navigate history after load completes
wc.once('did-finish-load', () => {
if (wc.canGoBack()) wc.goBack()
})
})
Executing JavaScript and Capturing Results
// Main process
win.webContents.once('did-finish-load', async () => {
const title = await win.webContents.executeJavaScript('document.title')
console.log('Page title:', title)
})
This invokes WebContentsImpl::ExecuteJavaScript in the C++ layer, which executes the code in the renderer's context and returns the value as a Promise.
Sending and Receiving IPC Messages
// Main process
win.webContents.on('ipc-message', (event, channel, ...args) => {
if (channel === 'renderer-hello') {
console.log('Renderer says:', args[0])
// Reply back to renderer
win.webContents.send('main-reply', 'got it')
}
})
In the renderer process (preload script):
const { ipcRenderer } = require('electron')
ipcRenderer.send('renderer-hello', 'world')
ipcRenderer.on('main-reply', (event, msg) => {
console.log('Main replied:', msg)
})
Controlling Zoom Levels
// Set 150% zoom
win.webContents.setZoomFactor(1.5)
// Retrieve current zoom level
const level = win.webContents.getZoomLevel()
console.log('Zoom level:', level)
Handling Permission Requests
const { session } = require('electron')
session.defaultSession.setPermissionRequestHandler((webContents, permission, callback) => {
if (permission === 'media') {
// Allow camera/microphone only for trusted origins
const allowed = webContents.getURL().startsWith('https://trusted.example')
callback(allowed)
} else {
callback(false)
}
})
This handler validates requests using the web_contents_permission_helper.cc implementation before granting access to protected resources.
Key Source Files
The following files in the electron/electron repository define the WebContents implementation:
lib/browser/api/web-contents.ts: Public JavaScript API exposed to developers (new BrowserWindow().webContents).shell/browser/web_contents_impl.handshell/browser/web_contents_impl.cc: C++ wrapper that forwards JavaScript calls to Chromium'scontent::WebContents.shell/browser/web_contents_permission_helper.cc: Handles permission request callbacks from the renderer.shell/common/web_contents_utility.mojom: Mojo interface definitions for IPC between browser and renderer processes.lib/browser/api/web-contents-view.ts: Wrapper for embedding WebContents inside aBrowserView.
Summary
- The WebContents API is accessed via
browserWindow.webContentsand serves as the control interface for web pages in Electron. - All navigation commands (
loadURL,reload,goBack) are implemented inweb-contents.tsand forwarded toWebContentsImplin the browser process. - JavaScript injection uses
executeJavaScript(), which returns a Promise resolved by the C++ layer inweb_contents_impl.cc. - IPC communication relies on
send()for main-to-renderer messaging and theipc-messageevent for renderer-to-main communication. - Permissions are handled at the session level but reference specific
webContentsinstances to determine access rights for camera, microphone, and other protected features.
Frequently Asked Questions
What is the difference between BrowserWindow and WebContents?
BrowserWindow is a high-level abstraction that creates and manages a native OS window, including the frame, menus, and toolbar. WebContents represents the actual web page rendered inside that window. When you create a BrowserWindow, Electron internally creates a WebContents instance and attaches it to the window property win.webContents. You control the page content through webContents, while you control the window chrome through BrowserWindow methods.
How do I execute JavaScript in a web page and get the result?
Use webContents.executeJavaScript(code), which returns a Promise that resolves with the evaluation result. For example: const result = await win.webContents.executeJavaScript('document.title'). This method injects the code into the renderer process and marshals the return value back to the main process via the IPC bridge implemented in shell/browser/web_contents_impl.cc.
Can I control webContents without a visible BrowserWindow?
Yes, you can create a WebContents instance without attaching it to a visible window using webContents.create() (though this is less common), or you can create a BrowserWindow with show: false. Hidden windows are useful for background tasks, preloading content, or offscreen rendering. The webContents API functions identically whether the window is visible or hidden.
How do permissions work with WebContents?
Permissions (camera, microphone, notifications) are requested by the renderer process and handled by the main process through session.setPermissionRequestHandler(). The handler receives the webContents instance as the first argument, allowing you to inspect the requesting URL via webContents.getURL() before calling the callback with true (allow) or false (deny). The validation logic resides in shell/browser/web_contents_permission_helper.cc.
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:
curl -s "https://instagit.com/install.md" Maintain an open-source project? Get it listed too →