By Admin on Saturday, 11 April 2026
Category: All

Microsoft Edge WebView2 Delphi

TsgcWebView2 is a new visual Delphi component that wraps Microsoft Edge WebView2, giving you a modern Chromium-based browser engine inside any VCL application. Drop it on a form, set a URL, and you have a fully featured embedded browser — complete with cookie management, download control, JavaScript integration, print support, and more.

Unlike the built-in TEdgeBrowser that ships with recent Delphi versions, TsgcWebView2 supports every Delphi version from Delphi 7 through Delphi 13 — the broadest version support of any WebView2 wrapper available. It is part of the sgcWebSockets library by eSeGeCe.

This article covers its feature set, shows practical code examples, compares it head-to-head with TEdgeBrowser, and explains its internal architecture.

Feature Overview

TsgcWebView2 exposes a wide surface area of the WebView2 SDK through clean Delphi events and methods. Here are the twelve major capability groups:

Navigation
Navigate, GoBack, GoForward, Reload, Stop. Supports POST navigation with custom headers and request bodies.
JavaScript Execution
Run JavaScript asynchronously or synchronously. Register init scripts that execute on every page load automatically.
Cookie Management
Get, add, update, and delete cookies programmatically. Full access to cookie attributes including domain, path, and expiry.
Download Control
Events for download start, progress, and completion. Redirect downloads to custom paths or cancel them entirely.
Profile Management
Multi-profile support for isolated browsing sessions. Clear browsing data (cache, cookies, history) per profile.
Print Support
Print the current page to PDF or show the system print dialog. Control paper size, orientation, and margins.
Audio / Mute Control
Detect when the document is playing audio. Toggle mute state programmatically without affecting the system volume.
Certificate Handling
Respond to client certificate requests and server certificate errors through dedicated events.
Context Menu
Intercept and fully customize the right-click context menu. Add, remove, or replace menu items with your own actions.
Favicon Access
Retrieve the current page favicon URI. React to favicon changes through a dedicated event.
Virtual Host Mapping
Map custom hostnames to local folders. Serve local HTML/CSS/JS files as if they came from a real web server.
Screenshot Capture
Save the visible page content as a PNG or JPEG image. Useful for thumbnails, reports, or automated testing.

Getting Started

The simplest way to use TsgcWebView2 is to drop it on a VCL form and call Navigate. The component handles WebView2 environment creation, controller initialization, and view binding automatically.

// Drop TsgcWebView2 on your form, then:
procedure TForm1.FormCreate(Sender: TObject);
begin
  sgcWebView2.Navigate('https://www.example.com');
end;

procedure TForm1.sgcWebView2NavigationCompleted(Sender: TObject;
  aIsSuccess: Boolean; aWebErrorStatus: Integer);
begin
  if aIsSuccess then
    Caption := sgcWebView2.DocumentTitle;
end;

The OnNavigationCompleted event fires after the page finishes loading, reporting whether navigation succeeded and any error status code. This is the natural place to update your UI — window title, status bar, back/forward button state — based on the loaded page.

Note. The component creates the WebView2 environment lazily on first use. If you need to configure environment options (browser folder, language, command-line switches), set them via the EnvironmentOptions property before calling Navigate.

Cookie Management

The CookieManager sub-object exposes the full WebView2 cookie API. You can list cookies for the current URL, add or update cookies with specific attributes, and delete individual cookies or clear them all at once.

// List cookies for the current page
sgcWebView2.CookieManager.GetCookies(sgcWebView2.URL);

// Delete all cookies
sgcWebView2.CookieManager.DeleteAllCookies;

// Add a cookie
sgcWebView2.CookieManager.AddOrUpdateCookie(
  'session', 'abc123', '.example.com', '/');

When you call GetCookies, the results arrive asynchronously in the OnCookiesReceived event. Each cookie includes its name, value, domain, path, expiry, secure flag, and HTTP-only flag. This is one of the features that TEdgeBrowser does not expose at all.

Tip. Use AddOrUpdateCookie to inject authentication tokens before navigating to a protected page. This avoids the need for a login form flow in embedded browser scenarios.

JavaScript Integration

TsgcWebView2 provides three approaches to JavaScript execution, each suited to a different use case:

Asynchronous Execution

Call ExecuteScript and handle the result in the OnScriptExecuted event. This is the standard, non-blocking approach.

// Async execution — result arrives in OnScriptExecuted event
sgcWebView2.ExecuteScript('document.title');

procedure TForm1.sgcWebView2ScriptExecuted(Sender: TObject;
  const aResult: string; aErrorCode: Integer);
begin
  if aErrorCode = 0 then
    ShowMessage('Title: ' + aResult);
end;

Synchronous Execution

When you need the result immediately, use ExecuteScriptSync. This blocks the calling thread until the script completes and returns the result directly.

var
  vTitle: string;
begin
  vTitle := sgcWebView2.ExecuteScriptSync('document.title');
  Caption := vTitle;
end;

Init Scripts

Init scripts are registered once and execute automatically on every page load. They run before any page JavaScript, making them ideal for injecting global configuration or polyfills.

// Runs on every page load, before any page scripts
sgcWebView2.AddInitScript('window.appVersion = "1.0";');

Download Management

Downloads are handled through an event-driven model. When a download begins, the OnDownloadStarting event lets you redirect the file to a custom path, cancel it, or let it proceed with defaults. A separate OnDownloadCompleted event fires when the download finishes.

procedure TForm1.sgcWebView2DownloadStarting(Sender: TObject;
  const aURI, aResultFilePath: string;
  var aCancel: Boolean;
  var aHandled: Boolean;
  var aFilePath: string);
begin
  // Redirect download to custom folder
  aFilePath := 'C:\Downloads\' + ExtractFileName(aResultFilePath);
  aHandled := True;
end;

procedure TForm1.sgcWebView2DownloadCompleted(Sender: TObject;
  const aFilePath: string; aState: Integer);
begin
  ShowMessage('Download complete: ' + aFilePath);
end;

Note. The aState parameter in OnDownloadCompleted indicates whether the download succeeded, was cancelled, or encountered an error. Check this value before processing the downloaded file.

POST Navigation & Custom Headers

Standard navigation loads a URL with a GET request. For API testing, form submission, or any scenario that requires a different HTTP method, NavigateWithPostData lets you specify the method, body, and headers in a single call.

// Navigate with POST data and custom headers
sgcWebView2.NavigateWithPostData(
  'https://api.example.com/submit',
  'POST',
  '{"key":"value"}',
  'Content-Type: application/json' + #13#10 +
  'Authorization: Bearer token123'
);

The headers parameter accepts a CRLF-delimited string, following the same format used by HTTP headers. This is useful for injecting authorization tokens, content types, or custom headers that your server expects.

Comparison with TEdgeBrowser

Delphi ships with TEdgeBrowser starting from Delphi 10.4 Sydney (available via GetIt for XE7+). It provides a basic WebView2 wrapper, but leaves many SDK features unexposed. The following table shows exactly where TsgcWebView2 goes further.

Feature TEdgeBrowser TsgcWebView2
Delphi Version Support XE7+ only D7 through D13
Cookie Management Full API
Download Progress Events Start / Progress / Complete
Profile / Clear Browsing Data
Audio / Mute Control
Favicon Access
Certificate Events
Basic Auth Events
Status Bar Text
Virtual Host Mapping
Shared Buffer
Synchronous ExecuteScript
Screenshot Capture
Init Script
POST Navigation
Print Support
Design-time Settings Throws if WebView not created Safe TPersistent properties
Context Menu PopupMenu merge Full event control
Graceful Degradation Per-feature version checks
Raw COM Access

TsgcWebView2 covers everything TEdgeBrowser offers and adds twelve features on top — cookie management, download events, profile control, audio/mute, favicon access, certificate handling, basic auth events, status bar text, virtual host mapping, shared buffer, full context menu control, and graceful degradation. It also supports Delphi versions going all the way back to Delphi 7, while TEdgeBrowser requires XE7 at minimum.

Important. TEdgeBrowser stores its settings directly on the COM interfaces. If you set a property at design time before the WebView2 environment is created, it throws an access violation. TsgcWebView2 avoids this entirely by using TPersistent sub-objects that buffer settings and apply them when the environment is ready.

Advanced Features

Print to PDF

Generate a PDF of the current page with a single method call. The output file is created asynchronously, and you can control paper size, margins, and orientation through parameters.

sgcWebView2.PrintToPdf('C:\output\page.pdf');

Screenshot Capture

Capture the visible area of the page as a PNG or JPEG image. The second parameter specifies the image format: 0 for PNG, 1 for JPEG.

sgcWebView2.CapturePreviewToFile('C:\screenshots\page.png', 0); // 0 = PNG

Virtual Host Mapping

Map a custom hostname to a local folder so that your embedded browser can load local files using standard HTTPS URLs. This avoids CORS issues and makes local content behave exactly like remote content.

// Serve local files via https://app.local/
sgcWebView2.SetVirtualHostNameToFolderMapping(
  'app.local', 'C:\MyApp\WebContent', 1);
sgcWebView2.Navigate('https://app.local/index.html');

Tip. Virtual host mapping is particularly useful for single-page applications. Bundle your HTML, CSS, and JavaScript with your Delphi application, then load it through a mapped hostname to get full access to web APIs that require a secure origin.

Audio and Mute Control

Detect when the loaded document is playing audio and toggle mute without affecting the system volume. This is useful for applications that embed media-heavy content.

sgcWebView2.IsMuted := True;

if sgcWebView2.IsDocumentPlayingAudio then
  ShowMessage('Audio is playing');

Architecture & Design

TsgcWebView2 is built on a clean three-layer architecture that separates concerns while keeping the developer-facing API simple:

For power users who need access to SDK features not yet wrapped by the component, the raw COM interfaces are available through the WebView, Controller, and Environment properties. You can call any COM method directly while still benefiting from the component's lifecycle management.

Graceful Degradation

Not every WebView2 feature is available in every version of the Edge runtime. TsgcWebView2 checks the installed runtime version at startup and exposes a Supports() method so you can query feature availability before calling it. This prevents runtime errors on machines with older Edge versions.

Design-time Safety

All configurable settings are exposed as TPersistent sub-objects. You can safely configure the component at design time in the Object Inspector without triggering COM initialization. Settings are buffered and applied automatically when the WebView2 environment is created at runtime.

Requirements

To use TsgcWebView2 in your application, you need:

Note. You can check whether the WebView2 runtime is installed before creating the component. If it is not present, you can direct the user to install it or fall back to an alternative browser control.

Conclusion

TsgcWebView2 is the most complete WebView2 wrapper available for Delphi. It is a strict superset of TEdgeBrowser, adding twelve features that Embarcadero's built-in component does not expose — cookie management, download events, profile control, audio detection, favicon access, certificate handling, basic authentication, status bar text, virtual host mapping, shared buffer, full context menu control, and graceful degradation.

It supports the broadest range of Delphi versions of any WebView2 wrapper, from Delphi 7 through Delphi 13. Whether you are maintaining a legacy application on an older compiler or building a new project on the latest Delphi, the same component and the same API work everywhere.

The API is designed to be easy to learn — drop the component on a form, call Navigate, and handle events — while remaining powerful enough for advanced scenarios through raw COM access and per-feature version checking. For Delphi developers who need a modern embedded browser, TsgcWebView2 is the natural choice.

Download Delphi Demo

Related Posts