jquery 点击浏览器后退按钮并显示确认框

ycggw6v2  于 2023-02-18  发布在  jQuery
关注(0)|答案(8)|浏览(215)

需要创建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);
    }

在这方面的任何帮助都将是非常值得赞赏的。

sbdsn5lh

sbdsn5lh1#

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

50few1ms2#

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

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

knsnq2tg3#

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

这对你有帮助。
DEMO

scyqe7ek

scyqe7ek4#

Robert摩尔的解决方案在刷新页面时导致了重复事件,可能是因为状态会被多次重新添加。
我通过只在状态为null时添加状态来解决这个问题,我还在返回之前清理了侦听器。

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

6ss1mwsb

6ss1mwsb5#

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

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

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

6kkfgxo0

6kkfgxo06#

这适用于所有情况,当
1.用户单击“后退”按钮并取消确认。
1.用户再次点击返回按钮并取消确认。
1.用户再次点击后退按钮并点击确定。
1.所以...

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
}
polhcujo

polhcujo7#

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 */}
    </>
}
zzlelutf

zzlelutf8#

试试这个

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

相关问题