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.
This is an expected behavior. window.scrollTop()
is a method in Jquery. If you want to use scrollTop, you must reference Jquery. For recording the scroll position and restoring the scroll position, you can use the ScrollTo
method to achieve it.
Here is an example of recording the top position through two buttons in Maui Balzor and restoring it through the second button. You can refer to this code snippet.
@inject IJSRuntime JsRuntime
<button class="btn btn-primary" @onclick="SaveScrollPosition">Click me</button>
//Long Content Here
<button class="btn btn-primary" @onclick="ScrollTo">Click me</button>
<script>
function saveScrollPosition() {
localStorage.setItem("scrollPosition", window.scrollY);
}
function restoreScrollPosition() {
if (localStorage.scrollPosition) {
var scrollPosition = localStorage.getItem("scrollPosition");
window.scrollTo(0,scrollPosition);
}
}
</script>
@code {
private async void SaveScrollPosition()
{
await JsRuntime.InvokeVoidAsync("saveScrollPosition");
}
private async void ScrollTo()
{
await JsRuntime.InvokeVoidAsync("restoreScrollPosition");
}
}