In a Blazor MAUI Hybrid app, I am trying to save the scroll position per page so that if returning to the page the saved scroll position is then reapplied.
I know that I should be saving it in session storage and per page, but I'm struggling to get the basic functionality to work.
One thing I tried throws the following exception:
Microsoft.JSInterop.JSException: window.scrollTop is not a function
TypeError: window.scrollTop is not a function
@inject NavigationManager NavManager
...
<script>
function saveScrollPosition() {
var scrollPosition = window.scrollTop();
localStorage.setItem("scrollPosition", scrollPosition);
}
function restoreScrollPosition() {
if (localStorage.scrollPosition) {
var scrollPosition = localStorage.getItem("scrollPosition");
window.scrollTop(scrollPosition);
}
}
</script>
...
@code{
protected override async Task OnInitializedAsync()
{
NavManager.LocationChanged += OnLocationChanged;
}
private async void OnLocationChanged(object sender, LocationChangedEventArgs e)
{
await JsRuntime.InvokeVoidAsync("saveScrollPosition");
}
}
And my previous attempt to register it at onbeforeunload and onload never fires.
<script>
window.onbeforeunload = function() {
var scrollPosition = window.scrollTop();
localStorage.setItem("scrollPosition", scrollPosition);
}
</script>
Does anyone have a pointer to what I'm missing? Basic window functions and events appear not to be working at all.