"test2-" + location.pathname}
+ />
+ >
+ );
+ },
+ children: testPages,
+ },
+ ],
+ { basename: "/base", window: testWindow }
+ );
+ let { container } = render();
+
+ expect(getHtml(container)).toMatch("On page 1");
+
+ // simulate scrolling
+ Object.defineProperty(window, "scrollY", { writable: true, value: 100 });
+
+ // leave page
+ window.dispatchEvent(new Event("pagehide"));
+ fireEvent.click(screen.getByText("Go to page 2"));
+ expect(getHtml(container)).toMatch("On page 2");
+
+ // return to page
+ window.dispatchEvent(new Event("pagehide"));
+ fireEvent.click(screen.getByText("Go to page 1"));
+
+ expect(getHtml(container)).toMatch("On page 1");
+
+ // check scroll activity
+ expect(mockScroll.mock.calls).toEqual([
+ [0, 0],
+ [0, 0],
+ [0, 100], // restored (still possible because the user hasn't left the page)
+ ]);
+
+ expect(consoleWarnMock).toHaveBeenCalledWith(
+ expect.stringContaining(
+ "Failed to save scroll positions in sessionStorage"
+ )
+ );
+
+ consoleWarnMock.mockRestore();
+ });
});
+const testPages = [
+ {
+ index: true,
+ Component() {
+ return (
+
+ On page 1
+ Go to page 2
+
+ );
+ },
+ },
+ {
+ path: "page",
+ Component() {
+ return (
+
+ On page 2
+ Go to page 1
+
+ );
+ },
+ },
+];
+
function getWindowImpl(initialUrl: string): Window {
// Need to use our own custom DOM in order to get a working history
const dom = new JSDOM(``, { url: "http://localhost/" });
diff --git a/packages/react-router-dom/index.tsx b/packages/react-router-dom/index.tsx
index e60e754e72..08b8e4cede 100644
--- a/packages/react-router-dom/index.tsx
+++ b/packages/react-router-dom/index.tsx
@@ -1323,10 +1323,17 @@ function useScrollRestoration({
let key = (getKey ? getKey(location, matches) : null) || location.key;
savedScrollPositions[key] = window.scrollY;
}
- sessionStorage.setItem(
- storageKey || SCROLL_RESTORATION_STORAGE_KEY,
- JSON.stringify(savedScrollPositions)
- );
+ try {
+ sessionStorage.setItem(
+ storageKey || SCROLL_RESTORATION_STORAGE_KEY,
+ JSON.stringify(savedScrollPositions)
+ );
+ } catch (error) {
+ warning(
+ false,
+ `Failed to save scroll positions in sessionStorage, will not work properly (${error}).`
+ );
+ }
window.history.scrollRestoration = "auto";
}, [storageKey, getKey, navigation.state, location, matches])
);