You can do that by setting a keylistener for the webview.
- Custom a keylistener in the android part:
namespace BlazorApp.Platforms.Android
{
public class MyListener : Java.Lang.Object, IOnKeyListener
{
public bool OnKey(global::Android.Views.View v, [GeneratedEnum] Keycode keyCode, KeyEvent e)
{
if(keyCode == Keycode.Back && e.Action == KeyEventActions.Down)
{
return true; // this will cancel the back button pressed event
}
return false;
}
}
}
- And in the MainPage.xaml:
<BlazorWebView x:Name="webview" HostPage="wwwroot/index.html">
<BlazorWebView.RootComponents>
<RootComponent Selector="#app" ComponentType="{x:Type local:Main}" />
</BlazorWebView.RootComponents>
</BlazorWebView>
- Override the
OnHandlerChanged()
method in the MainPage.cs:
protected override void OnHandlerChanged()
{
base.OnHandlerChanged();
#if ANDROID
var web = webview.Handler.PlatformView as Android.Webkit.WebView;
web.SetOnKeyListener(new Platforms.Android.MyListener());
#endif
}
Update:
You can add a judgement before you cancel the back button event. Such as:
namespace BlazorApp.Platforms.Android
{
public class MyListener : Java.Lang.Object, IOnKeyListener
{
public bool OnKey(global::Android.Views.View v, [GeneratedEnum] Keycode keyCode, KeyEvent e)
{
if(keyCode == Keycode.Back && e.Action == KeyEventActions.Down)
{
string url = (v as gloabl::Android.Webkit.WebView).Url;
if(url.EndsWith("specialpage"));// the razor page s route is @page"/specialpage"
return true; // this will cancel the back button pressed event
}
return false;
}
}
}