Skip to content

WebContents

github-actions[bot] edited this page Oct 15, 2025 · 3 revisions

Render and control web pages.

Overview

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.

Key Methods

Page Loading

LoadURLAsync(string)

Parameters:

  • url - URL to load

Description: Loads the url in the window. The url must contain the protocol prefix.

LoadURLAsync(string, LoadURLOptions)

Parameters:

  • url - URL to load
  • options - Loading options

Description: Loads the url with additional options.

GetUrl()

Returns: URL of the loaded page

Description: Get the URL of the loaded page.

JavaScript Execution

ExecuteJavaScriptAsync(string, bool)

Parameters:

  • code - The code to execute
  • userGesture (optional) - If set to true simulate a user gesture

Returns: The result of the executed code

Description: Evaluates script code in page.

Developer Tools

OpenDevTools()

Description: Opens the devtools.

OpenDevTools(OpenDevToolsOptions)

Parameters:

  • openDevToolsOptions - Developer tools options

Description: Opens the devtools with options.

CSS Injection

InsertCSS(bool, string)

Parameters:

  • isBrowserWindow - Whether the webContents belong to a BrowserWindow
  • path - Absolute path to the CSS file location

Description: Inserts CSS into the web page.

Printing

GetPrintersAsync()

Returns: Array of available printers

Description: Get system printers.

PrintAsync(PrintOptions)

Parameters:

  • options (optional) - Print options

Returns: Whether the print operation succeeded

Description: Prints window's web page.

PrintToPDFAsync(string, PrintToPDFOptions)

Parameters:

  • path - Output file path
  • options (optional) - PDF generation options

Returns: Whether the PDF generation succeeded

Description: Prints window's web page as PDF.

Properties

Id

Type: int

Description: Gets the unique identifier for this web contents.

Session

Type: Session

Description: Manage browser sessions, cookies, cache, proxy settings, etc.

Events

OnCrashed

Description: Emitted when the renderer process crashes or is killed.

OnDidFinishLoad

Description: Emitted when the navigation is done, i.e. the spinner of the tab has stopped spinning, and the onload event was dispatched.

OnDidStartNavigation

Description: Emitted when any frame (including main) starts navigating.

OnDidNavigate

Description: Emitted when a main frame navigation is done.

OnWillRedirect

Description: Emitted when a server side redirect occurs during navigation.

OnDidRedirectNavigation

Description: Emitted after a server side redirect occurs during navigation.

OnDidFailLoad

Description: Emitted when the load failed.

InputEvent

Description: Emitted when an input event is sent to the WebContents.

OnDomReady

Description: Emitted when the document in the top-level frame is loaded.

Usage Examples

Page Loading

// 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}");

JavaScript Execution

// 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}");

Developer Tools

// Open dev tools
webContents.OpenDevTools();

// Open with specific options
webContents.OpenDevTools(new OpenDevToolsOptions
{
    Mode = DevToolsMode.Detached,
    Activate = true
});

CSS Injection

// Inject CSS file
webContents.InsertCSS(true, "styles/custom-theme.css");

// Inject CSS for BrowserView
webContents.InsertCSS(false, "styles/browser-view.css");

Printing Operations

// 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");
}

PDF Generation

// 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");
}

Navigation Monitoring

// 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}");
};

Content Interaction

// 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
};

Related APIs

Next Steps

Additional Resources

Clone this wiki locally