目标是在浏览器中单击后退按钮时显示警报。它仅在单击“后退”按钮之前,单击页面上的其他位置时才起作用,否则它将转到上一页而没有警告消息,我已在此处包含我的代码。我想在页面加载后返回。
$(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>
IAM使用此处的新闻
您可以使用onbeforeunload
事件来实现
使用jquery
$(window).bind('beforeunload', function(){
myFunction();
return 'Are you sure you want to leave?';
});
function myFunction(){
// Write your business logic here
console.log('hello');
}
<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>