我尝试检测浏览器或选项卡已关闭。在大型应用程序中运行一个功能的最佳方法是什么?
window.onbeforeunload = function () {
return "Do you want to close?";
};
您可以使用react钩子并在您的App.js中实现它。我称它为useBeforeUnload:D
import { useEffect } from 'react'
const useBeforeUnload = (
value: ((evt: BeforeUnloadEvent) => any) | string
) => {
const handleBeforeunload = (evt: BeforeUnloadEvent) => {
let returnValue
if (typeof value === 'function') {
returnValue = value(evt)
} else {
returnValue = value
}
if (returnValue) {
evt.preventDefault()
evt.returnValue = returnValue
}
return returnValue
}
useEffect(() => {
window.addEventListener('beforeunload', handleBeforeunload)
return () => window.removeEventListener('beforeunload', handleBeforeunload)
}, [])
}
export default useBeforeUnload