doc/articles/controls/WebView.md
Uno Platform supports two
WebViewcontrols - theWebView2control and the legacyWebView. For new development, we strongly recommendWebView2as it will get further improvements in the future.
WebView2 is supported on all Uno Platform targets.
You can include the WebView2 control anywhere in XAML:
<WebView2 x:Name="MyWebView" Source="https://platform.uno/" />
To manipulate the control from C#, first ensure that you call its EnsureCoreWebView2Async method:
await MyWebView.EnsureCoreWebView2Async();
Afterward, you can perform actions such as navigating to an HTML string:
MyWebView.NavigateToString("<html><body><p>Hello world!</p></body></html>");
To enable WebView on the -desktop target, add the WebView Uno Feature in your .csproj:
<UnoFeatures>
<!-- Existing features -->
+ WebView;
</UnoFeatures>
[!IMPORTANT] If your project's desktop builder in
Platforms/Desktop/Program.csuses.UseWindows(), you'll also need to add the<UnoUseWebView2WPF>true</UnoUseWebView2WPF>property for the integration to work. However, it is recommended to migrate to.UseWin32()for better performance and reliability.
In case of WebAssembly, the control is supported via a native <iframe> element. This means all <iframe> browser security considerations and limitations also apply to WebView:
frame-ancestors Content Security Policy can be used to allow embedding a site you have control over, while at the same time blocking third-party sites from embeddingX-FRAME-OPTIONS headerWhen a page is loaded inside the WebView2 control, you can execute custom JavaScript code. To do this, call the ExecuteScriptAsync method:
webView.NavigateToString("<div id='test' style='width: 10px; height: 10px; background-color: blue;'></div>");
// Renders a blue <div>
await webView.ExecuteScriptAsync("document.getElementById('test').style.backgroundColor = 'red';");
// The <div> is now red.
The method can also return a string result, with returned values being JSON-encoded:
await webView.ExecuteScriptAsync("1 + 1"); // Returns a string containing 2
await webView.ExecuteScriptAsync($"(1 + 1).toString()"); // Returns a string containing "2"
await webView.ExecuteScriptAsync("eval({'test': 1})"); // Returns a string containing {"test":1}
WebView2 enables sending web messages from JavaScript to C# on all supported targets. In your web page, include code that sends a message to the WebView2 control if available. Since Uno Platform runs on multiple targets, you need to use the correct approach for each. We recommend creating a reusable function like the following:
function postWebViewMessage(message){
try{
if (window.hasOwnProperty("chrome") && typeof chrome.webview !== undefined) {
// Windows
chrome.webview.postMessage(message);
} else if (window.hasOwnProperty("unoWebView")) {
// Android
unoWebView.postMessage(JSON.stringify(message));
} else if (window.hasOwnProperty("webkit") && typeof webkit.messageHandlers !== undefined) {
// iOS and macOS
webkit.messageHandlers.unoWebView.postMessage(JSON.stringify(message));
}
}
catch (ex){
alert("Error occurred: " + ex);
}
}
// Usage:
postWebViewMessage("hello world");
postWebViewMessage({"some": ['values',"in","json",1]});
Note: Make sure not to omit the
JSON.stringifycalls for Android, iOS, and macOS as seen in the snippet above, as they are crucial to transfer data correctly.
To receive the message in C#, subscribe to the WebMessageReceived event:
webView.WebMessageReceived += (s, e) =>
{
Debug.WriteLine(e.WebMessageAsJson);
};
The WebMessageAsJson property contains a JSON-encoded string of the data passed to postWebViewMessage above.
To load local web content bundled with the application, you can use the SetVirtualHostNameToFolderMapping method. This allows you to set a virtual hostname that maps to a folder within the package, from which the web content will be loaded:
await webView.EnsureCoreWebView2Async();
webView.CoreWebView2.SetVirtualHostNameToFolderMapping(
"UnoNativeAssets",
"WebContent",
CoreWebView2HostResourceAccessKind.Allow);
webView.CoreWebView2.Navigate("http://UnoNativeAssets/index.html");
This will navigate to the index.html file stored in the WebContent folder. This folder must be included in a platform-specific location on each platform:
YourApp.Windows project and all its contents should be set to Content build actionResources folder and all its contents should be set to BundleResource build actionAssets folder and all its contents should be set to AndroidAsset build actionTo avoid duplication, you can put the files in a non-project-specific location and add them via linking, e.g.:
<BundleResource Include="..\LinkedFiles\WebContent\css\site.css" Link="iOS\Resources\WebContent\css\site.css" />
The web files can reference each other in a relative path fashion, for example, the following HTML file:
<html>
<head>
<script src="js/site.js" type="text/javascript"></script>
</head>
<body>
...
</body>
</html>
Is referencing a site.js file inside the js subfolder.
From macOS, inspecting applications using WebView2 controls using the Safari Developer Tools is possible. Here's a detailed guide on how to do it. To make this work, enable this feature in your app by adding the following capabilities in your App.Xaml.cs:
public App()
{
this.InitializeComponent();
#if __IOS__
Uno.UI.FeatureConfiguration.WebView2.IsInspectable = true;
#endif
}
[!IMPORTANT]
This feature will only work for security reasons when the application runs in Debug mode.
In order to use WebView2 on Linux, you'll need to install libwebkit2gtk and libgtk3-0:
On Ubuntu 22.04:
sudo apt install libwebkit2gtk-4.0-37
On Ubuntu 24.04:
sudo apt install libgtk-3-0 libwebkit2gtk-4.1-dev
It's overall preferable to use libwebkit2gtk 4.1 whenever possible in order to get http headers support, if your environment allows for it.
When running on a Wayland environment, the WebView control requires the environment variable GDK_BACKEND to be set to x11 to function correctly.
export GDK_BACKEND=x11
dotnet run
The WebResourceRequested event allows you to intercept and modify HTTP requests made by the WebView. This is useful for scenarios like injecting custom headers, implementing authentication, or modifying request/response content.
To use WebResourceRequested, you must first add a filter specifying which URLs should trigger the event, then subscribe to the event:
await webView.EnsureCoreWebView2Async();
// Add a filter for all requests
webView.CoreWebView2.AddWebResourceRequestedFilter(
"*",
CoreWebView2WebResourceContext.All,
CoreWebView2WebResourceRequestSourceKinds.All);
// Subscribe to the event
webView.CoreWebView2.WebResourceRequested += (sender, args) =>
{
// Access request information
var uri = args.Request.Uri;
var method = args.Request.Method;
// Modify headers
args.Request.Headers.SetHeader("Authorization", "Bearer my-token");
args.Request.Headers.SetHeader("X-Custom-Header", "custom-value");
// Optionally provide a custom response
// args.Response = new CoreWebView2WebResourceResponse(...);
};
The AddWebResourceRequestedFilter method accepts three parameters:
"*" for all URLs, "https://api.example.com/*" for specific domains)All, Document, Image, Script, etc.)All, Document, etc.)[!IMPORTANT]
WebResourceRequestedhas significant platform-specific limitations. Review the table below to understand what is supported on each platform.
| Platform | Support Level | Header Read | Header Modify | Custom Response | Notes |
|---|---|---|---|---|---|
| Windows (Win32/WinAppSDK) | ✅ Full | ✅ | ✅ | ✅ | Full WebView2 support |
| Android | ⚠️ Partial | ✅ | ⚠️ | ✅ | Header modification requires re-fetching the resource with HttpClient (only safe for GET/HEAD requests). Session cookies are automatically synchronized. POST request bodies cannot be reliably re-fetched and are not reissued by the implementation, so header changes for POST requests are unsupported. |
| iOS | ⚠️ Limited | ✅ | ⚠️ | ❌ | Navigation request headers cannot be modified. However, JavaScript-initiated requests (fetch/XMLHttpRequest) support custom header injection. Only fires for main document navigation, not sub-resources. |
| macOS | ⚠️ Limited | ✅ | ⚠️ | ❌ | Header injection is supported for new requests only. Cannot modify existing request headers. |
| WebAssembly | ⚠️ Limited | ✅ | ⚠️ | ❌ | Only fetch/XMLHttpRequest requests can be intercepted. Standard HTML elements (img, script, link, etc.) cannot have headers modified. Same-origin policy and CORS restrictions apply. May miss requests made during initial page load. |
| Linux (X11) | ❌ None | ❌ | ❌ | ❌ | Not implemented. |
The implementation uses two mechanisms:
WebResourceRequested for main document navigation (read-only headers)window.fetch() and XMLHttpRequest.prototype to apply custom headers to AJAX requestsThis means you can inject authentication tokens into API calls made via JavaScript:
webView.CoreWebView2.WebResourceRequested += (sender, args) =>
{
// This will be applied to fetch() and XMLHttpRequest calls
args.Request.Headers.SetHeader("Authorization", "Bearer my-token");
};
When headers are modified, the resource is re-fetched using HttpClient. The implementation includes:
CookieManagerThis ensures authenticated sessions work correctly when using WebResourceRequested.
For HTML element requests that cannot be intercepted:
In some advanced scenarios, you may need to access the platform-specific native web view control directly — for example, to configure settings not exposed by the Uno Platform abstraction.
The WebView2 control template contains a single ContentPresenter named WebViewTemplateRoot. Each platform sets the Content of this presenter to its native web view control. You can retrieve it using VisualTreeHelper:
await myWebView.EnsureCoreWebView2Async();
var presenter = (ContentPresenter)VisualTreeHelper.GetChild(myWebView, 0);
var nativeControl = presenter.Content;
The type of nativeControl varies per platform:
| Platform | Native Control Type | Notes |
|---|---|---|
| Android | Android.Webkit.WebView | Standard Android WebView |
| iOS | WebKit.WKWebView | Via UnoWKWebView, which extends WKWebView |
| macOS (Skia) | MacOSNativeWebView | Internal wrapper using native WebKit via P/Invoke |
| Windows (Win32/Skia) | N/A | Uses a native HWND; not directly accessible via Content |
| Linux (X11) | N/A | Uses a GTK WebKit.WebView hosted in a separate window |
| WebAssembly | BrowserHtmlElement | An HTML <iframe> element |
#if __ANDROID__
await myWebView.EnsureCoreWebView2Async();
var presenter = (ContentPresenter)VisualTreeHelper.GetChild(myWebView, 0);
if (presenter.Content is Android.Webkit.WebView androidWebView)
{
// Access native Android WebView settings
androidWebView.Settings.BuiltInZoomControls = true;
androidWebView.Settings.DisplayZoomControls = false;
}
#endif
#if __IOS__
await myWebView.EnsureCoreWebView2Async();
var presenter = (ContentPresenter)VisualTreeHelper.GetChild(myWebView, 0);
if (presenter.Content is WebKit.WKWebView wkWebView)
{
// Access native WKWebView configuration
wkWebView.AllowsBackForwardNavigationGestures = true;
}
#endif
[!NOTE] The native control is only available after calling
EnsureCoreWebView2Async()and the control template has been applied. The internal types and access patterns may change in future releases.
When using the WebView2 and running on WinAppSDK, make sure to create an x64 or ARM64 configuration:
x64 or ARM64 solution configuration