显示window.confirm以防止更改URL

问题描述 投票:0回答:1

需要防止更改我的组件中的 url。因此,需要显示一条消息,如果用户选择取消 - 不要更改 URL,如果确定 - 更改 URL。我如何在下一个 13.4 中实现这个逻辑

这是我目前的逻辑,但行不通。我什至没有看到window.confirm消息

useEffect(() => {
const handleBeforeUnload = (event: BeforeUnloadEvent) => {
const mess = window.confirm('Are you sure you want to leave?');
event.returnValue = mess;
if (!mess) {
event.preventDefault();
       }
     };

window.addEventListener('beforeunload', handleBeforeUnload);

return () => {
window.removeEventListener('beforeunload', handleBeforeUnload);
     };

javascript next.js react-hooks onbeforeunload
1个回答
0
投票

这似乎对我有用,即使我在 StackOverflow 代码片段中尝试也是如此。

window.addEventListener('beforeunload', function (event) {
  const unsavedChanges = true;
  if (unsavedChanges) {
    const confirmationMessage = 'You have unsaved changes. Are you sure you want to leave?';
    event.returnValue = confirmationMessage;
    return confirmationMessage; 
  }
});
<button onclick="window.location.reload()">reload</button>

© www.soinside.com 2019 - 2024. All rights reserved.