I have implemented the following code in wwwroot
- index.html
:
"use strict";
(() => {
const modified_inputs = new Set;
const defaultValue = "defaultValue";
// store default values
addEventListener("beforeinput", (evt) => {
const target = evt.target;
if (!(defaultValue in target || defaultValue in target.dataset)) {
target.dataset[defaultValue] = ("" + (target.value || target.textContent)).trim();
}
});
// detect input modifications
addEventListener("input", (evt) => {
const target = evt.target;
let original;
if (defaultValue in target) {
original = target[defaultValue];
} else {
original = target.dataset[defaultValue];
}
if (original !== ("" + (target.value || target.textContent)).trim()) {
if (!modified_inputs.has(target)) {
modified_inputs.add(target);
}
} else if (modified_inputs.has(target)) {
modified_inputs.delete(target);
}
});
// clear modified inputs upon form submission
addEventListener("submit", (evt) => {
modified_inputs.clear();
// to prevent the warning from happening, it is advisable
// that you clear your form controls back to their default
// state with evt.target.reset() or form.reset() after submission
});
// warn before closing if any inputs are modified
addEventListener("beforeunload", (evt) => {
if (modified_inputs.size) {
const unsaved_changes_warning = "Changes you made may not be saved.";
evt.returnValue = unsaved_changes_warning;
return unsaved_changes_warning;
}
});
})();
Source:
https://stackoverflow.com/a/48238659/3850405
This works really well if I try to close the tab, reload or leave the site without using Blazor navigation.
What I would like to do is be able to catch events from these types of navigation events as well:
Navigation.NavigateTo("/");
<NavLink class="nav-link" href="" Match="NavLinkMatch.All">
<span class="oi oi-home" aria-hidden="true"></span> Home
</NavLink>
<MatButtonLink Href="/" Raised="true">Test navigation</MatButtonLink>
My example test code:
@page "/editor"
@using Markdig;
@inject NavigationManager Navigation
<div class="row">
<div class="col-6">
<textarea class="form-control" @bind-value="Body" @bind-value:event="oninput"></textarea>
<MatButtonLink Href="/" Raised="true">Test navigation</MatButtonLink>
<button @onclick="Navigate">
Test navigation 2
</button>
</div>
<div class="col-6">
@if (!string.IsNullOrWhiteSpace(Body))
{
@((MarkupString)Preview)
}
</div>
</div>
@code {
public string Body { get; set; }
public string Preview => Markdown.ToHtml(Body);
private void Navigate()
{
Navigation.NavigateTo("/");
}
}
Found a similar question that had tried
window.onbeforeunload
:Blazor Navigationmanager cancel navigation on locationchanged
There does not seem to be a fix for this at the moment but a location changing event for NavigationManger is committed for
.NET 6.0
. I hope it will be possible to catch this event on a global level in the application.https://github.com/dotnet/aspnetcore/issues/14962