浏览器后退按钮单击确认框

use*_*333 0 javascript jquery

需要创建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);
    }
Run Code Online (Sandbox Code Playgroud)

任何帮助都会非常明显.

chr*_*g91 7

/* 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);
    }  
});
Run Code Online (Sandbox Code Playgroud)


Vai*_*ool 5

window.onbeforeunload = function() {
    return "Leaving this page will reset the wizard";
};
Run Code Online (Sandbox Code Playgroud)

这会对你有帮助。

演示版


Rob*_*ore 5

试试这个:它很简单,你可以完全控制后退按钮.

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);
            }
        });    
    });
}
Run Code Online (Sandbox Code Playgroud)