点击浏览器的后退按钮,需要创建javascript确认弹出窗口。如果我单击“后退”按钮,则会弹出弹出窗口,说“您要继续吗?”。如果单击"is",则它将已重定向到上一页。

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

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

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

最佳答案

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

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

09-25 18:15
查看更多