jQuery 浏览器后退按钮点击确认框

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18141729/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 21:05:44  来源:igfitidea点击:

Browsers back button click with confirm box

javascriptjquery

提问by user2509333

Need to create the javascript confirm pop up on click of browsers back button. If I click on back button pop up will come up and say "you want to go ahead ?" if click on Yes then it would have redirected to previous page.

需要创建 javascript 确认在单击浏览器后退按钮时弹出。如果我点击后退按钮会弹出并说“你想继续吗?” 如果单击是,则它会重定向到上一页。

I have following code it is not working as per the requirement.

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

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

Any help in this would be really appreciable.

在这方面的任何帮助将是非常可观的。

回答by Robert Moore

Try this: it's simple and you get total control over the back button.

试试这个:这很简单,您可以完全控制后退按钮。

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

回答by chri3g91

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

回答by Vaibs_Cool

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

This would help you.

这会帮助你。

DEMO

演示

回答by Robin Drexler

It's possible to always display a confirmation box, when a user tries to leave the page. That also includes pressing the back button. Maybe that's a suitable quick-fix for your issue?

当用户试图离开页面时,始终显示一个确认框是可能的。这还包括按下后退按钮。也许这是适合您的问题的快速解决方案?

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

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

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

回答by span

The solution by Robert Moore caused duplicate events when refreshing the page for me. Presumably since the state would be re-added multiple times.

Robert Moore 的解决方案在为我刷新页面时导致重复事件。大概是因为状态会被重新添加多次。

I worked around it by only adding state if it is null. I also clean up the listener before going back.

我通过仅在状态为空时添加状态来解决它。我还在回去之前清理了听众。

    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 has a good read on managing state: https://developer.mozilla.org/en-US/docs/Web/API/History_API#The_pushState()_method

MDN 对管理状态有很好的了解:https: //developer.mozilla.org/en-US/docs/Web/API/History_API#The_pushState()_method

回答by Manish Chauhan

Try This,

尝试这个,

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