我创建了一个库,我可以轻松地将其包含在我的所有网站中,以便轻松访问此功能。
将这个类放在一个新的 C# 类库项目中,以便您可以从其他项目(网站)中引用它。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace MyNameSpace.ConfirmLeavePageScript
{
[DefaultProperty("TextToDisplay")]
[ToolboxData("<{0}:ServerControl1 runat=server></{0}:ServerControl1>")]
public class ConfirmLeavePageScript : WebControl
{
[Bindable(true)]
[Category("Appearance")]
[DefaultValue("Are you sure you want to leave this page?")]
[Localizable(true)]
public string TextToDisplay
{
get
{
String s = (String)ViewState["TextToDisplay"];
return ((s == null) ? "Are you sure you want to leave this page?" : s);
}
set
{
ViewState["TextToDisplay"] = value;
}
}
protected override void RenderContents(HtmlTextWriter output)
{
string script = @"
<script type='text/javascript'>
var confirmOnPageExit = function (e)
{
// If we haven't been passed the event get the window.event
e = e || window.event;
var message = '" + TextToDisplay + @"';
if(typeof ConfirmLeavePageMessage != 'undefined') //give client side the opportunity to overwrite the message instead of using message from ViewState.
{
message=ConfirmLeavePageMessage;
}
// For IE6-8 and Firefox prior to version 4
if (e)
{
e.returnValue = message;
}
// For Chrome, Safari, IE8+ and Opera 12+
return message;
};
function EnableConfirmOnPageExit()
{
// Turn it on - assign the function that returns the string
window.onbeforeunload = confirmOnPageExit;
}
function DisableConfirmOnPageExit()
{
// Turn it off - remove the function entirely
window.onbeforeunload = null;
}
</script>
";
output.Write(script);
}
}
}
您可以在您的网站项目中注册标签前缀,方法是将其放在您的 web.config 中。确保您的网站添加 C# 类库项目作为参考(将它们放在同一个解决方案中)。
<configuration>
<system.web>
<pages>
<controls>
<add tagPrefix="tna" assembly="ConfirmLeavePage" namespace="MyNameSpace.ConfirmLeavePageScript" />
</controls>
</pages>
</system.web>
</configuration>
然后,将控件放在内容页面的头部。
<head>
<tna:ConfirmLeavePageScript runat="server" TextToDisplay="Are you sure you want to leave without saving?" />
</head>
在检测是否已进行更改的 JavaScript 函数中,调用此函数:
EnableConfirmOnPageExit();
您还可以执行以下操作(我认为这是不言自明的):
<script type="text/javascript>
ConfirmLeavePageMessage="new message"; //set a custom message from JavaScript for the confirmation window
DisableConfirmOnPageExit(); //Disables the confirmation window (user can leave page without seeing the confirmation window)
</script>