next.js 显示窗口,确认以防止更改URL

ybzsozfc  于 2024-01-07  发布在  其他
关注(0)|答案(1)|浏览(171)

需要防止从我的组件更改URL。因此,需要显示一条消息,如果用户选择取消-不更改URL,如果确定-更改URL。我如何在接下来的逻辑13.4
这是我现在的逻辑,但它不起作用。我甚至没有看到窗口。确认消息

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);
     };

字符串

q5lcpyga

q5lcpyga1#

这似乎对我很有效,即使我在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; 
  }
});

个字符

相关问题