Issue
I have a project using MAUI Hybrid to produce an Android Application (apk). A blazorWebView is running in MAUI app, so that the code of pages is used by both Web Site (un Blazor Wasm) and MAUI app (MAUI + Blazor WebView).
A blazorWebView is included in MAUI App (code from MainPage.xaml) :
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:b="clr-namespace:Microsoft.AspNetCore.Components.WebView.Maui;assembly=Microsoft.AspNetCore.Components.WebView.Maui"
xmlns:local="clr-namespace:MyMauiBlazor"
x:Class="MyMauiBlazor.MainPage">
<b:BlazorWebView HostPage="wwwroot/index.html">
<b:BlazorWebView.RootComponents>
<b:RootComponent Selector="app" ComponentType="{x:Type local:Main}" />
</b:BlazorWebView.RootComponents>
</b:BlazorWebView>
</ContentPage>
On Android devices, is it possible to handle the Back Button pressed ?
Currently, the App closes, but I want to handle this event (ex : navigate to previous page). Is there a way to do this ?
Solution
I had the same problem as you, officially microsoft doesn't support back key navigation for MAUI blazor yet, but I found a temporary solution for that:
First you have to create a javascript file, and put it in the wwwroot folder, and include it in the index.html file. Inside the js file put this code:
window.goBack = () => {
history.go(-1);
}
Then you have to create a c# class and make it a service, so for example I created a class called GoBack.cs. To set it as a service just put this code in MauiProgram.cs:
builder.Services.AddTransient<GoBack>();
In the GoBack class you have to create a static variable and method, because otherwise you will not be able to use the IJSRuntime interop. My GoBack file is the following:
public class GoBack
{
private static IJSRuntime JSRuntime { get; set; }
public GoBack(IJSRuntime jSRuntime)
{
GoBack.JSRuntime = jSRuntime;
}
public static async Task GoBackInTime()
{
//Microsoft.Maui.Platform;
if (GoBack.JSRuntime != null)
{
await GoBack.JSRuntime.InvokeVoidAsync("goBack");
}
}
}
The method GoBackInTime is going to call the js method goBack through the jsInteroperability. Now you have to inject in the first blazor page that you load this service.
@inject GoBack goBack
This way the jsRuntime in the cs file will be initialized and not null.
Now all you have to do is override the OnBackButtonPressed method in MainPage.xaml.cs:
protected override bool OnBackButtonPressed()
{
GoBack.GoBackInTime();
return true;
}
This way, when the back button is pressed, it won't exit the application (because we are returning true) and at the same time the js function is called so the blazor page will navigate to the previous page.
Answered By - SimoPisa
Answer Checked By - Katrina (JavaFixing Volunteer)