How to notify an user when he tries to close a tab or close the browser

六眼飞鱼酱① 提交于 2020-01-05 07:11:22

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!