我一直试图找出最好的方法,没有太多运气。如果用户点击后退,例如显示自定义对话框,我想做点什么。
我尝试过这种方法在某种程度上有效:
var url = 'www.examples.com';
history.pushState(
{
pushStateUrl: url
},
url,
url
);
window.onpopstate = function() {
showDialog();
};
但它并不干净,因为它涉及操纵浏览器历史记录。有没有更好的方法来检测回来而不改变历史。
P.S。它不必在所有浏览器中工作。最好不要使用jquery。
在我的情况下,beforeunload也不起作用,因为我无法显示自己的自定义对话框。
答案 0 :(得分:0)
this is a late response but I am posting in the intention of this could help to someone like me
add **beforeunload** event lister for your page when loaded
and remove it when submitting the form or whenever you want
step 1: var stayOnPage =function(){
confirm("Would you like to save this draft?");
if (!stayOnPage) {
history.back() or
// do your stuff
} else {
// do your stuff
}
}
window.addEventListener('beforeunload',stayOnPage);
step 2: remove event listener when you want
function onSubmitForm(){
window.removeEventListener('beforeunload',stayOnPage);
}
<button onclick="onSubmitForm()"> Submit </button>
if this doesn't work
change beforeunload to popstate
i.e
function onSubmitForm(){
window.addEventListener('popstate', stayOnPage);
}
答案 1 :(得分:-2)
试试这个,发现here
window.onbeforeunload = onBack;
function onBack(evt)
{
if (evt == undefined)
evt = window.event;
if ( (evt.clientX < 0) ||
(evt.clientY < 0) ||
(evt.clientX > document.body.clientWidth) ||
(evt.clientY > document.body.clientHeight)
)
{
alert('Unload from browser button press');
return "You clicked some browser button? Do you want to move away from this page?";
}
return undefined;
}