2

我在 OnBeforeUnload 上调用一个函数并返回真/假。当我要关闭浏览器时,浏览器会显示消息“您确定要离开此页面吗”,在此下方写为“真/假”。

代码就像: -

<body   onbeforeunload="javascript:return unlockOperationon()">
</body>

而 JavaScript 函数是:-

function unlockOperationon()
{
    return true;
}
4

1 回答 1

2

您需要从 unlockOperationonMain 方法返回“True/False”字符串。的目的onbeforeunload是向用户询问有意义的消息,以便该消息的处理程序用于获取该消息。例如,您可以从处理程序返回此字符串:“此页面上所有未保存的更改都将丢失。”

这是此评论中提出的想法的实现:

<script runat="server" >
     [System.Web.Services.WebMethod]
     public static string GetBeforeUnloadMessage()
     {
          return DateTime.Now.Second < 30 ? "Please, stay with us at least for a few seconds." : null;
     }
</script>
<head runat="server">
     <title></title>
     <script src="Scripts/jquery-1.8.2.min.js" type="text/javascript"></script>
     <script type="text/javascript">
          function checkServerBeforeUnload() {
               var result = null;
               $.ajax({
                    url: location.href + "/GetBeforeUnloadMessage",
                    type: "POST",
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    async: false,
                    success: function (response) {
                         result = response.d;
                    }
               });

               if (result) {
                    return result;
               }
          }
     </script>
</head>
<body onbeforeunload="return checkServerBeforeUnload()">
     <form id="form1" runat="server">
     <div>
          Page rendered at:
          <%= DateTime.Now.ToString("HH:mm:ss") %>
          <asp:Button runat="server" Text="Click Me" />
     </div>
     </form>
</body>
</html>
于 2012-10-17T08:29:37.373 回答