Skip to content

[Bug]: Scroll Restoration not working on page refresh in mobile safari #9463

@fetters5

Description

@fetters5

What version of React Router are you using?

6.4.2

Steps to Reproduce

Scroll position is not maintained in mobile safari browsers upon reload of a page. This is due to using the beforeunload event which is not supported by ios safari

function useBeforeUnload(callback: () => any): void {
  React.useEffect(() => {
    window.addEventListener("beforeunload", callback);
    return () => {
      window.removeEventListener("beforeunload", callback);
    };
  }, [callback]);
}

By changing the above code to use the visibilitychange event and checking document.visibilityState === 'hidden' it seems to work as intended in safari

Reference material

https://developer.mozilla.org/en-US/docs/Web/API/Document/visibilitychange_event
https://www.igvita.com/2015/11/20/dont-lose-user-and-app-state-use-page-visibility/
https://levelup.gitconnected.com/how-to-send-an-asynchronous-request-at-the-end-of-a-page-session-90bf7229448c
https://tech.trivago.com/post/2020-11-17-exploringthepagevisibilityapifordetectin/

Expected Behavior

Expect that when reloading a page the scroll position will be maintained in ios safari

Actual Behavior

The scroll position goes to 0 since it was not captured.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions