NativeWebView
Overview
NativeWebView
is a control that provides a native web browser implementation for Avalonia and WPF applications. It wraps platform-specific web controls and provides a unified API for web browsing functionality.
Properties
Source
public Uri Source { get; set; }
The URI of the top-level document displayed in the WebView. Setting this property is equivalent to calling Navigate()
.
Default value: about:blank
CanGoBack
public bool CanGoBack { get; }
Indicates whether the WebView can navigate to a previous page in the navigation history.
CanGoForward
public bool CanGoForward { get; }
Indicates whether the WebView can navigate to a next page in the navigation history.
Events
NavigationCompleted
public event EventHandler<WebViewNavigationCompletedEventArgs>? NavigationCompleted;
Fires after navigation of the top-level document completes rendering, either successfully or unsuccessfully.
NavigationStarted
public event EventHandler<WebViewNavigationStartingEventArgs>? NavigationStarted;
Fires before a new navigation starts for the top-level document.
WebMessageReceived
public event EventHandler<WebMessageReceivedEventArgs>? WebMessageReceived;
Fires after web content sends a message to the app host via invokeCSharpAction(body)
.
Usage Example
Bi-directional JS<->C# communication example:
private async void NativeWebView_OnNavigationCompleted(object? sender, WebViewNavigationCompletedEventArgs e)
{
await ((NativeWebView)sender!).InvokeScript(""" invokeCSharpAction("{'key': 10}") """);
}
private void NativeWebView_OnWebMessageReceived(object? sender, WebMessageReceivedEventArgs e)
{
var message = e.Body;
// message == "{'key': 10}"
}
Methods
Navigate
public void Navigate(Uri url)
Navigates the WebView to the specified URI.
NavigateToString
public void NavigateToString(string text)
Renders the provided HTML string as the top-level document.
InvokeScript
public Task<string?> InvokeScript(string scriptName)
Executes the provided JavaScript in the top-level document.
Usage Example
<NativeWebView Source="https://avaloniaui.net/" NavigationCompleted="WebView_NavigationCompleted" />
private async void WebView_NavigationCompleted(object? sender, WebViewNavigationCompletedEventArgs args)
{
// Execute JavaScript
await webView.InvokeScript("alert('Hello World')");
}
GoBack
public bool GoBack()
Navigates to the previous page in navigation history. Returns false
if navigation is not possible.
GoForward
public bool GoForward()
Navigates to the next page in navigation history. Returns false
if navigation is not possible.
Refresh
public bool Refresh()
Reloads the current page.