Mafesoft.Maui.AdvancedWebView
1.2.0
See the version list below for details.
dotnet add package Mafesoft.Maui.AdvancedWebView --version 1.2.0
NuGet\Install-Package Mafesoft.Maui.AdvancedWebView -Version 1.2.0
<PackageReference Include="Mafesoft.Maui.AdvancedWebView" Version="1.2.0" />
<PackageVersion Include="Mafesoft.Maui.AdvancedWebView" Version="1.2.0" />
<PackageReference Include="Mafesoft.Maui.AdvancedWebView" />
paket add Mafesoft.Maui.AdvancedWebView --version 1.2.0
#r "nuget: Mafesoft.Maui.AdvancedWebView, 1.2.0"
#:package Mafesoft.Maui.AdvancedWebView@1.2.0
#addin nuget:?package=Mafesoft.Maui.AdvancedWebView&version=1.2.0
#tool nuget:?package=Mafesoft.Maui.AdvancedWebView&version=1.2.0
AdvancedWebView
AdvancedWebView is a lightweight WebView for .NET MAUI (Android and iOS). It extends the built-in MAUI WebView, so navigation events, cookies and user agent keep working, and it adds platform settings that the standard control does not expose.
Requirements
- .NET 10
- Android 5.0 (API 21) or later
- iOS 15 or later
Installation
dotnet add package Mafesoft.Maui.AdvancedWebView
Register the handler in MauiProgram.cs:
using Mafesoft.Maui.Controls;
builder
.UseMauiApp<App>()
.UseAdvancedWebView();
Usage
<ContentPage xmlns:awv="clr-namespace:Mafesoft.Maui.Controls;assembly=Mafesoft.Maui.AdvancedWebView">
<awv:AdvancedWebView
x:Name="WebView"
Source="https://dotnet.microsoft.com"
JavaScriptEnabled="True"
ScrollBouncesEnabled="False"
Navigating="OnNavigating" />
</ContentPage>
// Block a URL
void OnNavigating(object sender, WebNavigatingEventArgs e)
{
if (e.Url.StartsWith("https://ads.")) e.Cancel = true;
}
// Clear the HTTP cache
WebView.ClearCache();
Properties
| Property | Default | Android | iOS | Notes |
|---|---|---|---|---|
JavaScriptEnabled |
true |
✔ | ✔ | iOS: read when the view is created |
JavaScriptCanOpenWindowsAutomatically |
false |
✔ | ✔ | iOS: read when the view is created |
ScrollBouncesEnabled |
false |
✔ | ✔ | Android: overscroll glow |
MediaPlaybackRequiresUserGesture |
false |
✔ | ✔ | iOS: read when the view is created |
AllowsInlineMediaPlayback |
true |
✔ | Read when the view is created | |
AllowMixedContent |
false |
✔ | HTTP resources in HTTPS pages | |
AllowFileAccess |
false |
✔ | file:// and content:// URLs |
|
CacheMode |
Default |
✔ | Default, NoCache, CacheOnly, CacheElseNetwork |
|
NewWindowBehavior |
OpenInSameView |
✔ | ✔ | target="_blank" and window.open: OpenInSameView, OpenInBrowser, Cancel |
Inherited from the MAUI WebView: Source, UserAgent, Cookies, Navigating, Navigated, EvaluateJavaScriptAsync, GoBack, GoForward, Reload.
Page state
Read-only bindable properties, updated by the web view on Android and iOS:
| Property | Type | Description |
|---|---|---|
Progress |
double |
Load progress of the current page, from 0 to 1 |
IsLoading |
bool |
Whether a page is loading |
Title |
string? |
document.title; null when the page has none |
CurrentUrl |
string? |
URL of the current page; also follows history.pushState, which does not raise Navigated |
<ProgressBar Progress="{Binding Progress, Source={x:Reference WebView}}"
IsVisible="{Binding IsLoading, Source={x:Reference WebView}}" />
<Label Text="{Binding Title, Source={x:Reference WebView}}" />
<Label Text="{Binding CurrentUrl, Source={x:Reference WebView}}" />
New windows
Links with target="_blank" and calls to window.open(url) follow NewWindowBehavior. Handle NewWindowRequested to decide per URL:
webView.NewWindowBehavior = NewWindowAction.OpenInSameView; // default
webView.NewWindowRequested += (s, e) =>
{
// e.Url, e.IsUserGesture
if (!e.Url.StartsWith("https://shop.example.com"))
e.Action = NewWindowAction.OpenInBrowser; // OpenInSameView, OpenInBrowser, Cancel
};
OpenInSameViewraisesNavigatingas a normal navigation, so URLs you block there stay blocked.window.openwithout a user gesture is blocked by the web view whileJavaScriptCanOpenWindowsAutomaticallyisfalse(the default).window.open()without a URL is ignored.- iOS does not report the user gesture of
window.open.IsUserGestureistruefor links, and forwindow.openwhileJavaScriptCanOpenWindowsAutomaticallyisfalse; otherwisewindow.openis reported asfalse. - Android: a form with
target="_blank"andmethod="post"opened in the same view is loaded as a GET, without its body. iOS keeps the POST.
External links
The web view cannot load tel:, mailto: and other app links, and shows an error page for them. AdvancedWebView hands them to the system instead. It can also send web sites you do not own to the system browser:
webView.ExternalSchemes = ["tel", "mailto", "sms", "geo", "maps", "whatsapp", "intent", "market", "itms-apps"]; // default
webView.InternalHosts = ["example.com", "*.example.com"]; // default: empty, every site stays inside
webView.ExternalLinkOpening += (s, e) =>
{
// e.Url, e.Reason (Scheme or Host)
e.Cancel = true; // the system does not open it, and the web view does not load it: handle it yourself
};
Navigatingis raised first. A URL cancelled there is not opened outside either.InternalHosts:"example.com"matches that host only,"*.example.com"its subdomains only. Only the top-level page is checked, so iframes from other hosts still load. Links opened as new windows in the same view follow the same rules.- Android
intent://URLs open the app they name, limited to activities that accept browser links (as Chrome does). When no app handles them, the web view loads theirS.browser_fallback_url. - Links leave the app through MAUI
Launcher.OpenAsync. On iOS a scheme likewhatsapp:opens only if the app is installed. You do not needLSApplicationQueriesSchemesor Android<queries>entries for this.
Load failures and error page
webView.NavigationFailed += (s, e) =>
{
// e.Url, e.Error, e.HttpStatusCode, e.Description
if (e.Error == WebNavigationError.HttpError && e.HttpStatusCode == 404)
e.ShowErrorPage = false; // keep the server's own 404 page
};
webView.ErrorPageHtml = """
<h1>Page not available</h1>
<p>{{description}}</p>
<button onclick="AdvancedWebView.retry()">Retry</button>
""";
webView.ServerCertificateError += (s, e) => e.Proceed = false; // default: reject
WebNavigationError |
Android | iOS (NSURLErrorDomain) |
|---|---|---|
NoInternet |
net::ERR_INTERNET_DISCONNECTED |
-1009, -1020, -1005 |
Timeout |
ERROR_TIMEOUT |
-1001 |
HostNotFound |
ERROR_HOST_LOOKUP, ERROR_CONNECT |
-1003, -1004, -1006 |
SslError |
ERROR_FAILED_SSL_HANDSHAKE, rejected certificate |
-1200 … -1206 |
HttpError |
HTTP status ≥ 400 | HTTP status ≥ 400 |
Cancelled |
net::ERR_ABORTED |
-999, WebKit 102 |
Unknown |
anything else | anything else |
- Only the top-level page is reported. Failures of iframes and of resources such as images are not.
ErrorPageHtmlplaceholders:{{url}},{{description}},{{error}},{{statusCode}}. They are HTML-encoded. The page is shown for every error exceptCancelled. Sete.ShowErrorPage = falseto keep the current page.AdvancedWebView.retry()loads the failed URL again as a normal navigation, so it raisesNavigating. It needs JavaScript and the bridge. The error page is local content, so it can use the bridge whateverBridge.AllowedOriginssays.- Invalid certificates are rejected unless a
ServerCertificateErrorhandler setse.Proceed = true. Do this only during development, for example for a local server with a self-signed certificate. Accepting every certificate exposes the connection to interception, and Google Play rejects apps that do it.
Platform delegates
On Android, AdvancedWebView sets subclasses of MAUI's MauiWebViewClient and MauiWebChromeClient; on iOS, subclasses of MauiWebViewNavigationDelegate and MauiWebViewUIDelegate. If your app replaces them, page state, new windows, external links and error handling stop working.
Methods
| Method | Description |
|---|---|
ClearCache() |
Clears the HTTP cache (memory and disk). Cookies and local storage are kept. |
LoadUrl(url, headers) |
Loads a page with extra HTTP headers. |
PostUrlAsync(url, content, headers) |
Loads a page with a POST request. |
Headers and POST
webView.LoadUrl("https://example.com/account", new Dictionary<string, string>
{
["Authorization"] = $"Bearer {token}",
});
await webView.PostUrlAsync("https://example.com/login", new FormUrlEncodedContent(new Dictionary<string, string>
{
["user"] = "mario",
}));
NavigatingandNavigatedare raised as for a link, and the external-link rules apply.- The headers go with this request only. They are not sent with the page's resources (images, scripts, API calls) or with later navigations, such as links the user taps. For an authenticated session, prefer a cookie (
Cookies). - Android only posts
application/x-www-form-urlencodedbodies, and cannot add headers to a POST.PostUrlAsyncthrowsNotSupportedExceptionotherwise. iOS supports any content type and headers. - Call these methods after the control is loaded (for example in its
Loadedevent). Before that, they throwInvalidOperationException.
JavaScript bridge
The page and the app can exchange messages and call each other, with local HTML and with the remote sites you allow. The bridge object window.AdvancedWebView is injected into every page before the page's own scripts run.
Allowed origins (read this first)
Local content (an HtmlWebViewSource or files packaged with the app) can always use the bridge. Remote sites cannot, until you list them:
webView.Bridge.AllowedOrigins = ["https://shop.example.com", "https://*.example.com"];
webView.Bridge.AllowSubframes = false; // default: iframes cannot use the bridge
Rules are https://example.com, https://example.com:8443, https://*.example.com (subdomains only, not example.com) or * (any site, not recommended). Messages from other origins are dropped, with a warning in the log, and their invoke calls fail with OriginNotAllowed.
Messages
// Page -> app
webView.MessageReceived += (s, e) =>
{
string text = e.Message; // a posted string, or the JSON of a posted object
var order = e.GetJson<Order>(); // System.Text.Json, camelCase
Uri? origin = e.Origin; // e.g. https://shop.example.com
};
// App -> page
await webView.PostMessageAsync("plain text");
await webView.PostMessageAsync(new { type = "cart-updated", count = 3 });
AdvancedWebView.postMessage({ type: "checkout", total: 42.5 });
AdvancedWebView.addEventListener("message", e => console.log(e.data));
Calling C# from the page
webView.RegisterHandler<UserRequest, User>("getUser", async (req, ct) =>
await api.GetUserAsync(req!.Id, ct) ?? throw new BridgeException("NotFound", $"User {req.Id} does not exist."));
webView.RegisterHandler("logout", async ct => await auth.LogoutAsync());
try {
const user = await AdvancedWebView.invoke("getUser", { id: 1 });
} catch (err) {
console.error(err.code, err.message); // "NotFound", "User 1 does not exist."
}
err.code |
When |
|---|---|
MethodNotFound |
No handler with that name |
InvalidArguments |
The arguments do not match the handler's request type |
Timeout |
The handler ran longer than webView.Bridge.InvokeTimeout (default 30 s) |
HandlerError |
The handler threw an exception; err.message is the exception message |
OriginNotAllowed |
The page's origin is not in Bridge.AllowedOrigins |
| your code | The handler threw BridgeException(code, message) |
Calls still running when the page navigates away are cancelled through the handler's CancellationToken.
Only the exception message reaches the page; set webView.Bridge.IncludeExceptionDetails = true while debugging to get the full text in err.details.
For trimming and Native AOT, every method has an overload that takes a JsonTypeInfo<T> from a JsonSerializerContext, and RegisterRawHandler works on JSON text.
Calling page functions from C#
int total = await webView.InvokeJavaScriptAsync<int>("cart.getTotal");
await webView.InvokeJavaScriptAsync("app.showToast", "Saved", 3000);
// Trimming/AOT: arguments as a JSON array, result through a JsonSerializerContext
User? user = await webView.InvokeJavaScriptAsync("app.getUser", AppJsonContext.Default.User, "[42]");
Arguments are passed as JSON data, never concatenated into the script, so quotes and newlines are safe. If the function returns a Promise it is awaited. Errors thrown by the function (or a rejected Promise, or a missing function) raise JavaScriptException with the message and JavaScriptStack; no answer within Bridge.InvokeTimeout raises TimeoutException. This works on any page, whatever AllowedOrigins says, because the app makes the call.
Injecting scripts and styles
webView.UserScripts.Add(new UserScript("document.documentElement.classList.add('in-app');"));
webView.UserScripts.Add(new UserScript
{
File = "inject.js", // Resources/Raw/inject.js
InjectionTime = UserScriptInjectionTime.DocumentStart,
AllowedOrigins = ["https://*.example.com"], // empty = every page
});
webView.UserStyleSheets.Add(".cookie-banner { display: none !important; }");
<awv:AdvancedWebView.UserScripts>
<awv:UserScript File="inject.js" InjectionTime="DocumentStart" />
</awv:AdvancedWebView.UserScripts>
Scripts run on every page load; changes apply from the next load. DocumentStart scripts run before the page's own scripts, DocumentEnd scripts (the default) when the DOM is ready. MainFrameOnly (default true) keeps a script out of iframes. A script restricted with AllowedOrigins is wrapped in an if block: var and functions stay global, top-level let/const become block-scoped.
Notes
- Android needs an Android System WebView that supports
WebMessageListener(any reasonably recent version); otherwise the bridge is disabled and a warning is logged. On WebViews without document-start scripts the bridge is injected when the page finishes loading: page scripts should wait forAdvancedWebView.readyor theadvancedwebviewreadyevent.
Sample app
samples/AdvancedWebView.Sample has two tabs:
- Browser: page title, URL and progress bar (
Title,CurrentUrl,Progress,IsLoading), switches for the properties, cache mode and new-window pickers, switches forInternalHostsandErrorPageHtml,ClearCache(),LoadUrlwith headers andPostUrlAsync(against httpbin.org, which echoes the request), URL blocking inNavigating,EvaluateJavaScriptAsync, and a local test page foralert(),confirm(), atarget="_blank"link,window.open(), load failures (HTTP 404 and 500, unknown host, expired certificate, timeout), external links (tel:,mailto:,geo:,intent://),document.titlechanges andhistory.pushState. - Bridge: messages both ways, handlers with results and error codes,
InvokeJavaScriptAsync(plain, Promise, error), a user style sheet, and a user script on example.com that shows the bridge blocked or allowed byAllowedOrigins.
dotnet build samples/AdvancedWebView.Sample -t:Run -f net10.0-android
Tests
The bridge core and its JavaScript side are tested end to end without a device: the script runs in Jint and talks to the real C# core.
dotnet test --project tests/AdvancedWebView.Tests/AdvancedWebView.Tests.csproj
License
| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| .NET | net10.0-android36.0 is compatible. net10.0-ios26.0 is compatible. |
-
net10.0-android36.0
- Microsoft.Maui.Controls (>= 10.0.120)
- Xamarin.AndroidX.WebKit (>= 1.14.0.1)
-
net10.0-ios26.0
- Microsoft.Maui.Controls (>= 10.0.120)
NuGet packages
This package is not used by any NuGet packages.
GitHub repositories
This package is not used by any popular GitHub repositories.