1.beforeunload
concept:
当浏览器窗口关闭或者刷新时,会触发beforeunload事件。此事件使网页能够触发一个确认对话框,询问用户是否真的要离开该页面。如果用户确认,浏览器将导航到新页面,否则导航将会取消。
usage:
window.addEventListener('beforeunload', e => {e.returnValue = ''; }attention:
为避免意外弹出窗口,除非页面已与之交互,否则浏览器可能不会显示在beforeunload事件中创建的提示,甚至根本不会显示它们; HTML5规范指出在此事件处理函数中,对于window.alert(), window.confirm(), 和 window.prompt() 的调用会被忽略。
2. <Prompt>
concept:
Used to prompt the user before navigating away from a page
usage:
<Prompt
when={formIsHalfFilledOut} // true || false
message="Are you sure you want to leave?"
/><Prompt
message={location =>
location.pathname.startsWith("/app") // location: 即将跳转的location
? true // 允许跳转
: `Are you sure you want to go to ${location.pathname}?`
}
/>