浏览器确认关闭:取消按钮也会关闭浏览器

Browser confirm closing: cancel button also closes the browser

本文关键字:浏览器 按钮 确认 取消      更新时间:2023-09-26

我的页面里有一个表单。我想在有人关闭浏览器时确认关闭。如果用户单击"确定"按钮,则应提交表单并关闭浏览器。如果用户单击取消按钮/关闭确认框,则不应发生任何操作。这是我的代码:

<!DOCTYPE html>
<html>
<script language="JavaScript">
function closeEditorWarning(){
if(confirm('Are you sure want to close this window'))
{
document.quiz.submit();
}
}
window.onbeforeunload = closeEditorWarning;
</script>
<form name="quiz" action="Hello.html" method="get" target="_blank">
  First name: <input type="text" name="fname"><br>
  Last name: <input type="text" name="lname"><br>
  <input type="submit" value="Submit">
</form>
<p>Click on the submit button, and the input will be open "hello.html".</p>
</body>
</html>

但困境是,我在单击取消按钮/关闭确认框时关闭了浏览器。请帮忙。

您无法通过 comfirm() 控制关闭事件。

但是,您可以在按事件离开此页面之前进行确认。

function closeEditorWarning(e){
    e = e || window.event;
    e.returnValue = 'Are you sure want to close this window?';
}