[英]How to show alert on browser back button click event using jquery
我想在浏览器中单击后退按钮时显示警报。 它仅在单击后退按钮之前有效,当您单击页面上的其他位置时,否则,它将 go 返回到上一页而没有警告消息。
我在这里添加了我的代码。 我想在页面加载时返回 go。
$(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
您可以使用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>
把它放在你的 JS 文件中,它就会工作。当你按下浏览器的后退按钮时,它会提醒你离开或取消。
$(window).bind('beforeunload', function(){
return '>>>>>Before You Go<<<<<<<< \n Your custom message go here';
});
history.pushState(null, document.title, location.href); window.addEventListener("popstate", function (event) { $.confirm({ boxWidth: "30%", title: "Alert", model: true, content: "The Changes made will be cleared", buttons: { Continue: function () { history.back(); }, Cancel: function () { history.pushState(null, document.title, location.href); }, }, }); });
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.