问题
First of all, I always say the same: sorry about my english is very weak. I hope you can understand me well.
I need to notify an user when he tries to close a tab or close the browser. Is there any way to fire an event to avoid the browser will be closed? The application is made in silverlight.
Thanks in advance.
回答1:
Take a look at the following example, there is also a sample application:
http://www.blog.jonnycornwell.com/2011/01/23/using-silverlight-and-javascript-to-prevent-leaving-a-webpage/
It's about using Silverlight and JavaScript to prevent leaving a webpage.
The javascript:
<script language="javascript" type="text/javascript">
window.onbeforeunload = askConfirm;
function askConfirm() {
var control = document.getElementById("silverlightControl");
var preventLeave = control.Content.Page.PreventLeave();
if (!preventLeave) {
return;
}
var message = control.Content.Page.LeaveRequested();
return message;
}
</script>
The silverlight code:
public MainPage()
{
InitializeComponent();
HtmlPage.RegisterScriptableObject("Page", this);
}
[ScriptableMember]
public string LeaveRequested()
{
return "You have unsaved changes to your current document?";
}
[ScriptableMember]
public bool PreventLeave()
{
return (bool)PreventLeaveCheckBox.IsChecked;
}
回答2:
This can be done easily with javascript. For example:
<html>
<head>
<script type="text/javascript">
<!--
function closeIt(url,name)
{
return "Hi there! I'm a message!";
}
window.onbeforeunload = closeIt;
// -->
</script>
</head>
<body>
<p>I'm a webpage!</p>
</body>
</html>
来源:https://stackoverflow.com/questions/12277717/how-to-notify-an-user-when-he-tries-to-close-a-tab-or-close-the-browser