1. 程式人生 > >關閉瀏覽器時觸發自定義函式

關閉瀏覽器時觸發自定義函式

 
<script type="text/javascript" language="javascript">
    function getEvent() //同時相容ie和ff的寫法, 這個方法是捕獲瀏覽器關閉事件
    {
        if(document.all)   return window.event;
        func=getEvent.caller;
        while(func!=null){
            var arg0=func.arguments[0];
            if(arg0)
            {
                if((arg0.constructor==Event || arg0.constructor ==MouseEvent) || (typeof

(arg0)=="object" && arg0.preventDefault && arg0.stopPropagation))
                {
                    return arg0;
                }
            }
            func=func.caller;
        }
        return null;
    }

    function MyConfirm() {//彈出關閉提示
        if (window.confirm('確定要關閉頁面嗎?')) {
            Ext.Ajax.request({
                url: 'quit.aspx',  //quit.aspx該頁面用於處理邏輯,呼叫自定義函式
                method: 'POST',
                success: onSuccess,
                failure: onSuccessf
            });
        }
        else {
            return false;
        }
    }

    function onSuccess(request, options) {
        var result = Ext.util.JSON.decode(request.responseText);
        window.location = result.Data.url;

        Ext.Msg.show(1);
    }

    function onSuccessf(request, options) {
        Ext.Msg.show(2);
    }

    function ConfirmClose() {
        if(window.event)
            window.event.returnValue = "在關閉視窗前確認您是否已經儲存了資訊!";
        else
            getEvent().preventDefault();//for firefox
    }

    function on_page_loaded()   //自己定義的body的onload事件 
    {
        try{
            if(!window.onbeforeunload )    //為了不覆蓋原來的onbeforeunload方法,先判斷
                //window.onbeforeunload = ConfirmClose;   //todo 增加了視窗關閉前的提示
                window.onbeforeunload = MyConfirm;   //todo 增加了視窗關閉前的提示
        }catch(e){}
    }
</script>

<body onload="on_page_loaded()">

需要匯入ext-base.js和ext.js
<script type="text/javascript" src="../js/ext2.3/adapter/ext/ext-base.js"></script>
<script type="text/javascript" src="../js/ext2.3/ext.js"></script>