浏览器后退按钮点击时带有确认框。

5

需要在浏览器返回按钮单击时创建JavaScript确认弹出窗口。如果我单击后退按钮,弹出窗口将出现并说“您想继续吗?”如果单击“是”,则会重定向到上一页。

我有以下代码,它不能按照要求工作。

if(window.history && history.pushState){ // check for history api support
        window.addEventListener('load', function(){

            // create history states
            history.pushState(-1, null); // back state
            history.pushState(0, null); // main state
            history.pushState(1, null); // forward state
            history.go(-1); // start in main state

            this.addEventListener('popstate', function(event, state){
                // check history state and fire custom events
                if(state = event.state){

                    event = document.createEvent('Event');
                    event.initEvent(state > 0 ? 'next' : 'previous', true, true);
                    this.dispatchEvent(event);

                    var r = confirm("Would you like to save this draft?");
                    if(r==true) { 
                        // Do nothing      

                    } else {  
                       self.location = document.referrer;    
                    }
                    // reset state
                    history.go(-state);

                }
            }, false);
        }, false);
    }

任何帮助都将不胜感激。

8个回答

12
/* Prevent accidental back navigation click */
history.pushState(null, document.title, location.href);
window.addEventListener('popstate', function (event)
{
    const leavePage = confirm("you want to go ahead ?");
    if (leavePage) {
        history.back(); 
    } else {
        history.pushState(null, document.title, location.href);
    }  
});

无法正常工作... - Shurvir Mori

9
试试这个:它很简单,而且你可以完全控制后退按钮。
if (window.history && history.pushState) {
    addEventListener('load', function() {
        history.pushState(null, null, null); // creates new history entry with same URL
        addEventListener('popstate', function() {
            var stayOnPage = confirm("Would you like to save this draft?");
            if (!stayOnPage) {
                history.back() 
            } else {
                history.pushState(null, null, null);
            }
        });    
    });
}

这个程序可以运行,但是如果我刷新当前页面,就会得到一个空白页面。 - srinivas gowda
确认框如果用户选择了“确定”选项,则返回true。因此,您的条件应进行更改。例如:if(leavePage) - chri3g91
这就是我一直在寻找的。它可以在各种浏览器中运行。 - Gianfranco Fertino
无法正常工作... - Shurvir Mori

5
window.onbeforeunload = function() {
    return "Leaving this page will reset the wizard";
};

这会给您帮助。

演示


1
它在新的浏览器中不起作用,因为它们不再允许自定义消息。 - Robert Moore

2

Robert Moore提供的解决方案在我刷新页面时导致了重复事件。可能是因为状态被多次重新添加。

我通过仅在状态为空时添加状态来解决了这个问题。我还在返回之前清理了侦听器。

    window.onload = function () {
        if (window.history && history.pushState) {
            if (document.location.pathname === "/MyBackSensitivePath") {
                if (history.state == null) {
                    history.pushState({'status': 'ongoing'}, null, null);
                }
                window.onpopstate = function(event) {
                    const endProgress = confirm("This will end your progress, are you sure you want to go back?");
                    if (endProgress) {
                        window.onpopstate = null;
                        history.back();
                    } else {
                        history.pushState(null, null, null);
                    }
                };
            }
        }
    };

MDN有一篇关于管理状态的好文章:https://developer.mozilla.org/en-US/docs/Web/API/History_API#The_pushState()_method


这个可以工作。确保你更改/MyBackSensitivePath。 - Nandostyle

1

当用户尝试离开页面时,可以始终显示确认框,包括按下后退按钮。也许这是您问题的适当快速修复方法?

window.addEventListener('beforeunload', function() {
    return 'You really want to go ahead?';
}); 

http://jsfiddle.net/squarefoo/8SZBN/1/


这对我也没用,我使用了 window.onbeforeunload = function() ... 然后就可以了。 - Cesar Alonso

1

这适用于所有情况,包括:

  1. 用户点击“返回”按钮并取消确认。
  2. 用户再次点击“返回”按钮并取消确认。
  3. 用户再次点击“返回”按钮并点击“确定”。
  4. 以此类推...
public componentDidMount(): void {
    history.pushState(null, 'PageName', window.location.href)
    window.onpopstate = (e: PopStateEvent) => {
        if (confirm('Are you sure you want to leave?')) {
            window.onpopstate = (e) => {
                history.back()
            }
            
            history.back()
        } else {
            history.pushState(null, 'PageName', window.location.href)
        }
    }
}
       
public componentWillUnmount(): void {
    window.onpopstate = null
}

0

chri3g91提供的解决方案对我来说是以上解决方案中最好的,但当我在我的NextJS项目中测试解决方案时,它存在一个问题,即返回按钮被永久禁用,即使我点击“OK”按钮也无法返回,因为它又创建了一个新的“confirm”。

我对解决方案进行了一些更改,现在它完美地运行!

import React, { useEffect } from "react"

function confirmBack() {
    if (confirm('Your current game progress will be lost!')) {
        window.removeEventListener('popstate', confirmBack);
        window.history.back()
    } else window.history.pushState(null, document.title, location.href) // preventing back for next click
}

export default function Component() {
    useEffect(() => {
        window.history.pushState(null, document.title, location.href); // preventing back initially
        window.addEventListener('popstate', confirmBack);
        return () => { window.removeEventListener('popstate', confirmBack) };
    }, [])

    return <>
        {/* JSX Content */}
    </>
}

-1

试试这个,

window.onbeforeunload = function() {
  return "You're leaving the site.";
};
$(document).ready(function() {
  $('a[rel!=ext]').click(function() {
    window.onbeforeunload = null;
  });
});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接