Skip to content

Commit 20160fa

Browse files
committed
fix: use pagehide event
Closes #7
1 parent 82dfef9 commit 20160fa

File tree

1 file changed

+23
-11
lines changed

1 file changed

+23
-11
lines changed

src/index.tsx

Lines changed: 23 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,22 @@
11
import * as React from 'react'
22
import { useCallback, useEffect } from 'react'
3-
import { useBeforeUnload, useLocation, useNavigation } from 'react-router-dom'
3+
import { useLocation, useNavigation } from 'react-router-dom'
44

5-
type Direction = "vertical" | "horizontal";
6-
type ScrollAttribute = "scrollTop" | "scrollLeft";
5+
type Direction = 'vertical' | 'horizontal'
6+
type ScrollAttribute = 'scrollTop' | 'scrollLeft'
77
const DIRECTION: { [direction in Direction]: ScrollAttribute } = {
88
vertical: 'scrollTop',
99
horizontal: 'scrollLeft',
10-
};
10+
}
1111

1212
export function ElementScrollRestoration({
1313
elementQuery,
14-
direction = "vertical",
14+
direction = 'vertical',
1515
...props
16-
}: { elementQuery: string; direction?: Direction } & React.HTMLProps<HTMLScriptElement>) {
16+
}: {
17+
elementQuery: string
18+
direction?: Direction
19+
} & React.HTMLProps<HTMLScriptElement>) {
1720
const STORAGE_KEY = `position:${elementQuery}`
1821
const navigation = useNavigation()
1922
const location = useLocation()
@@ -61,11 +64,18 @@ export function ElementScrollRestoration({
6164
}
6265
}, [STORAGE_KEY, elementQuery, navigation.state, updatePositions])
6366

64-
useBeforeUnload(() => {
65-
updatePositions()
66-
})
67+
useEffect(() => {
68+
window.addEventListener('pagehide', updatePositions)
69+
return () => {
70+
window.removeEventListener('pagehide', updatePositions)
71+
}
72+
}, [updatePositions])
6773

68-
function restoreScroll(storageKey: string, elementQuery: string, scrollAttribute: ScrollAttribute) {
74+
function restoreScroll(
75+
storageKey: string,
76+
elementQuery: string,
77+
scrollAttribute: ScrollAttribute,
78+
) {
6979
const element = document.querySelector(elementQuery)
7080
if (!element) {
7181
console.warn(`Element not found: ${elementQuery}. Cannot restore scroll.`)
@@ -95,7 +105,9 @@ export function ElementScrollRestoration({
95105
dangerouslySetInnerHTML={{
96106
__html: `(${restoreScroll})(${JSON.stringify(
97107
STORAGE_KEY,
98-
)}, ${JSON.stringify(elementQuery)}, ${JSON.stringify(scrollAttribute)})`,
108+
)}, ${JSON.stringify(elementQuery)}, ${JSON.stringify(
109+
scrollAttribute,
110+
)})`,
99111
}}
100112
/>
101113
)

0 commit comments

Comments
 (0)