Blazor通过JavaScript的API和C#代码的交互来劫持浏览器的Back按钮。具体实现步骤如下:
window.interceptBackButton = function() {
DotNet.invokeMethodAsync('AssemblyName', 'OnBackButtonPressed');
}
@inject IJSRuntime jsRuntime
@code {
private async Task InterceptBackButton() {
await jsRuntime.InvokeVoidAsync("interceptBackButton");
}
}
protected override async Task OnInitializedAsync() {
await jsRuntime.InvokeVoidAsync("localStorage.setItem", "currentUrl", NavigationManager.Uri);
}
protected override async Task OnAfterRenderAsync(bool firstRender) {
if (firstRender) {
await jsRuntime.InvokeVoidAsync("window.addEventListener", "popstate", "function(event) {if(localStorage.getItem('currentUrl') !== window.location.href) {InterceptBackButton();}}");
}
}
[JSInvokable]
public async Task OnBackButtonPressed()