星期三, 3月 13, 2013

[jQuery API] 偵測關閉網頁使用者點選ok或cancel

為了避免使用者在網頁處理中關閉網頁的話,可以綁定onbeforeunload事件來偵測,
但更進一步的應用,可能需要了解使用者到底是按ok還是cancel!!
找到以下這篇所用到的解法,有需要的人可以參考看看。

Way to know if user clicked Cancel on a Javascript onbeforeunload Dialog?
The code within the first setTimeout method has a delay of 1ms. This is just to add the function into the UI queue. Since setTimeout runs asynchronously the Javascript interpreter will continue by directly calling thereturn statement, which in turn triggers the browsers modal dialog. This will block the UI queue and the code from the first setTimeout is not executed, until the modal is closed. If the user pressed cancel, it will trigger another setTimeout which fires in about one second. If the user confirmed with ok, the user will redirect and the second setTimeout is never fired.

$(function(){ 
 
 $(window).bind("beforeunload", function(e) {
  setTimeout(function() {
  
            setTimeout(function() {
                $("body").css('background-color', 'red').html("User click cancel button");
            }, 1000);
        },1);
        return 'are you sure';
 });
 
 //按ok處理
 $(window).unload( function () { 
  console.log('bye bye :)');
  
 } );
 
});

沒有留言:

張貼留言

留個話吧:)

其他你感興趣的文章

Related Posts with Thumbnails