调用asp.net按钮从onbeforeunload javascript中单击

调用asp.net按钮从onbeforeunload javascript中单击,javascript,html,asp.net,validation,Javascript,Html,Asp.net,Validation,我的iframe内容aspx页面包含3个asp元素:textbox,RequiredFieldValidator,与textbox和按钮关联, 在javascript onbeforeunload中,我想调用按钮单击事件,该事件在文本框为空时阻止离开页面 但以下代码不起作用: <script type="text/javascript"> window.onbeforeunload = function (e) { document.getElementById("Button1")

我的iframe内容aspx页面包含3个asp元素:textbox,RequiredFieldValidator,与textbox和按钮关联, 在javascript onbeforeunload中,我想调用按钮单击事件,该事件在文本框为空时阻止离开页面

但以下代码不起作用:

<script type="text/javascript">
window.onbeforeunload = function (e) {
document.getElementById("Button1").click();
}
</script>
<asp:textbox runat='server' id="TextBox1" AutoPostBack="true"/>
<asp:Button ID="Button1" runat="server" Text="Button" onclick="TextBox1_Click" />
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server"    ErrorMessage="RequiredFieldValidator" ControlToValidate="TextBox1"></asp:RequiredFieldValidator>

window.onbeforeunload=函数(e){
document.getElementById(“Button1”)。单击();
}

onbeforeunload
事件处理程序是特殊的。您不能无条件地阻止用户离开页面。

您应该从此处理程序返回非void值-最好是
string
-如果用户确实想离开页面,系统将提示用户。大多数浏览器都会在弹出窗口中显示返回的字符串

<script type="text/javascript">
window.onbeforeunload = function (e) {
    return "The textbox is empty. Are you sure you wan't to leave the page?";
}
</script>

window.onbeforeunload=函数(e){
return“文本框为空。您确定不离开该页吗?”;
}
这种不寻常行为的原因是安全。必须通知用户到另一页的导航被中断。否则他/她可能会认为导航成功。
假设您悄悄地取消了这个处理程序中的导航,并将页面内容更改为类似于Internet银行应用程序。用户实际想要访问银行应用程序的可能性很小。但它可能会发生。这打开了劫持用户凭证的大门。所以在网络浏览器中是不可能的


基本上,在
onbeforeunload
事件处理程序中,所有通常会停止导航到另一个页面的操作都无效-它们被忽略,这是有意的。

dosent work?“onbeforeunload”中的文本框是空的,因此验证程序停止单击callI我想停止卸载并显示验证消息,有什么办法吗?@mich我编辑了我的答案,解释了与您想要的行为相关的安全隐患。但是,客户端可以单击“确定”并离开页面。是的,您对此无能为力。用户控制浏览器并始终可以离开页面。