-
Notifications
You must be signed in to change notification settings - Fork 0
WebContents
Render and control web pages.
The Electron.WebContents API provides control over web page content within Electron windows. It handles page loading, navigation, JavaScript execution, and web page lifecycle events.
Gets the unique identifier for this web contents.
Manage browser sessions, cookies, cache, proxy settings, etc.
Evaluates script code in page.
In the browser window some HTML APIs like requestFullScreen can only be invoked by a gesture from the user. Setting userGesture to true will remove this limitation.
Code execution will be suspended until web page stop loading.
Parameters:
-
code- The code to execute -
userGesture- if set totruesimulate a user gesture
Returns:
The result of the executed code.
Get system printers.
Returns:
Array of available printers.
Get the URL of the loaded page.
It's usefull if a web-server redirects you and you need to know where it redirects. For instance, It's useful in case of Implicit Authorization.
Returns:
URL of the loaded page.
Inserts CSS into the web page.
See: https://www.electronjs.org/docs/api/web-contents#contentsinsertcsscss-options
Works for both BrowserWindows and BrowserViews.
Parameters:
-
isBrowserWindow- Whether the webContents belong to a BrowserWindow or not (the other option is a BrowserView) -
path- Absolute path to the CSS file location
Loads the url in the window. The url must contain the protocol prefix.
The async method will resolve when the page has finished loading, and rejects if the page fails to load.
A noop rejection handler is already attached, which avoids unhandled rejection errors.
Loads the url in the window. The url must contain the protocol prefix, e.g. the http:// or file://. If the load should bypass http cache then use the pragma header to achieve it.
Parameters:
-
url- URL to load
Loads the url with additional options.
The async method will resolve when the page has finished loading, and rejects if the page fails to load.
A noop rejection handler is already attached, which avoids unhandled rejection errors.
Loads the url in the window. The url must contain the protocol prefix, e.g. the http:// or file://. If the load should bypass http cache then use the pragma header to achieve it.
Parameters:
-
url- URL to load -
options- Loading options
Opens the devtools.
Opens the devtools with options.
Parameters:
-
openDevToolsOptions- Developer tools options
Prints window's web page.
Parameters:
-
options- Print options
Returns:
Whether the print operation succeeded.
Prints window's web page as PDF with Chromium's preview printing custom settings.The landscape will be ignored if @page CSS at-rule is used in the web page. By default, an empty options will be regarded as: Use page-break-before: always; CSS style to force to print to a new page.
Parameters:
-
path- Output file path -
options- PDF generation options
Returns:
Whether the PDF generation succeeded.
Emitted when an input event is sent to the WebContents.
Emitted when the renderer process crashes or is killed.
Emitted when the load failed.
Emitted when the navigation is done, i.e. the spinner of the tab has stopped spinning, and the onload event was dispatched.
Emitted when a main frame navigation is done.
Emitted after a server side redirect occurs during navigation.
Emitted when any frame (including main) starts navigating.
Emitted when the document in the top-level frame is loaded.
Emitted when a server side redirect occurs during navigation.
// Load URL with options
await webContents.LoadURLAsync("https://example.com", new LoadURLOptions
{
UserAgent = "MyApp/1.0",
ExtraHeaders = "Authorization: Bearer token123"
});
// Load local file
await webContents.LoadURLAsync("file://" + Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "app/index.html"));
// Get current URL
var currentUrl = await webContents.GetUrl();
Console.WriteLine($"Current URL: {currentUrl}");// Execute simple JavaScript
var result = await webContents.ExecuteJavaScriptAsync("document.title");
Console.WriteLine($"Page title: {result}");
// Execute with user gesture simulation
await webContents.ExecuteJavaScriptAsync("document.requestFullscreen()", true);
// Execute complex code
var userAgent = await webContents.ExecuteJavaScriptAsync("navigator.userAgent");
Console.WriteLine($"User agent: {userAgent}");// Open dev tools
webContents.OpenDevTools();
// Open with specific options
webContents.OpenDevTools(new OpenDevToolsOptions
{
Mode = DevToolsMode.Detached,
Activate = true
});// Inject CSS file
webContents.InsertCSS(true, "styles/custom-theme.css");
// Inject CSS for BrowserView
webContents.InsertCSS(false, "styles/browser-view.css");// Print web page
var printSuccess = await webContents.PrintAsync(new PrintOptions
{
Silent = false,
PrintBackground = true,
DeviceName = "My Printer"
});
if (printSuccess)
{
Console.WriteLine("Print job sent successfully");
}// Generate PDF
var pdfSuccess = await webContents.PrintToPDFAsync("document.pdf", new PrintToPDFOptions
{
MarginsType = PrintToPDFMarginsType.None,
PageSize = PrintToPDFPageSize.A4,
PrintBackground = true,
Landscape = false
});
if (pdfSuccess)
{
Console.WriteLine("PDF generated successfully");
}// Monitor navigation events
webContents.OnDidStartNavigation += (url) =>
{
Console.WriteLine($"Starting navigation to: {url}");
};
webContents.OnDidNavigate += (navInfo) =>
{
Console.WriteLine($"Navigated to: {navInfo.Url}");
};
webContents.OnDidFinishLoad += () =>
{
Console.WriteLine("Page finished loading");
};
webContents.OnDidFailLoad += (failInfo) =>
{
Console.WriteLine($"Page failed to load: {failInfo.ErrorCode} - {failInfo.ErrorDescription}");
};// Wait for DOM ready
webContents.OnDomReady += () =>
{
Console.WriteLine("DOM is ready");
// Safe to execute DOM-related JavaScript now
};
// Handle page crashes
webContents.OnCrashed += (killed) =>
{
Console.WriteLine($"Renderer crashed, killed: {killed}");
// Optionally reload the page
};- Electron.WindowManager - Windows containing web contents
- Electron.Session - Session management for web contents
- Electron.IpcMain - Communication with web contents
- Electron WebContents Documentation - Official Electron web contents API
- Web Content Management - Understanding web content handling
- Security Considerations - Secure web content integration
Want to contribute to this documentation? Please fork and create a PR! The Wiki is autogenerated from the /docs content in the repository.