我想在浏览器中单击后退按钮时显示警报。仅在单击后退按钮之前,当您单击页面上的其他位置时,此选项才起作用;否则,它将在没有警报消息的情况下跳至上一页。
我在这里添加了我的代码。我想在页面加载后返回。
$(document).ready(function() {
if (window.history && window.history.pushState) {
//window.history.pushState('', null, './');
window.history.pushState(null, "", window.location.href);
$(window).on('popstate', function() {
alert('Warning! Your data will lose.');
document.location.href = 'www.redirecturl.com';
});
}
});
<html>
<head>
<title>Disable Browser Back Button Using JavaScript</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.10.2/jquery-ui.min.js">
</script>
</head>
<body>
<a href="Page2.html">Click Here...</a>
</body>
</html>
我在这里使用JQuery
答案 0 :(得分:0)
您可以使用onbeforeunload
事件
使用jQuery
$(window).bind('beforeunload', function(){
myFunction();
return 'Are you sure you want to leave?';
});
function myFunction(){
// Write your business logic here
alert('Bye');
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p>Close this window, press F5 or click on the link below to invoke the onbeforeunload event.</p>
<a href="https://www.w3schools.com">Click here to go to w3schools.com</a>
使用JavaScript
window.onbeforeunload = s => "";
<body>
<p>Close this window, press F5 or click on the link below to invoke the onbeforeunload event.</p>
<a href="https://www.w3schools.com">Click here to go to w3schools.com</a>
</body>
答案 1 :(得分:0)
将其放在您的JS文件中,它将起作用..当您按浏览器的后退按钮时,它将提醒您离开或取消。
$(window).bind('beforeunload', function(){
return '>>>>>Before You Go<<<<<<<< \n Your custom message go here';
});