Tại sao jquery $(window).unload không hoạt động? | Why jquery $(window).unload is not working?

Hôm nay nhân được một vấn đề khá hay từ thằng bạn, vấn đề là khi đóng trang web hoặc khi trang web được làm mới nó muốn hiển thị một câu thông báo để tạm biệt người dùng, và bạn tôi sử dụng sự kiện jquery [$(window).unload] để giải quyết vấn đề này, nhưng rất tiếc nó không hoạt động.

Problem - Vấn đề:

<!DOCTYPE html>
<html>
<head>
    <title>VNLIVES.NET | Why jquery $(window).unload is not working?</title>
    <script type='text/javascript' src='http://code.jquery.com/jquery-1.10.1.js'></script>
</head>
<body>

<h1>Welcome to VNLIVES.NET</h1>
<p>Close this window or press F5 to reload the page.</p>
<p><strong>Note:</strong> Due to different browser settings, this event may now always work as exepcted.</p>

<script type='text/javascript'>
    $(window).unload(function(){
       alert( "Google Bye You!" );
    });
</script>

</body>
</html>

Với đoạn mã trên khi chạy trên FireFox 21.0, hay một số trình duyệt khác bạn sẽ không nhận bất kỳ thông báo nào. Từ đó ta sẽ cho rằng câu lệnh [$(window).unload] không hoạt đông như hình bên dưới.


Tuy nhiên thật sự vấn đề không nằm ở câu lệnh mờ mằn ở trình duyệt, một số trình duyệt vì các lý do nào đó đã chặn thông báo(alert) cho trường hợp này, nhưng cũng có vài trình duyệt nó thật sự sự không chạy luôn ví dụ như các bản FireFox version gần đây.

Thí dụ nếu bạn sử dụng trình duyệt IE Version 7.0 thì sẽ thấy được thông báo như script đã định nghĩa như hình bên dưới.



Solution - Giải pháp:

Sau tham khảo ý kiến trên các diễn đàn khác nhau thì giải pháp được nhiều người đông tình nhất là thay đổi cách xử lý sang sự kiển event và return như sau.

<!DOCTYPE html>

<html>

<head>

    <title>VNLIVES.NET | Why jquery $(window).unload is not working?</title>

    <script type='text/javascript' src='http://code.jquery.com/jquery-1.10.1.js'></script>

</head>

<body>

<h1>Welcome to VNLIVES.NET</h1>

<p>Close this window or press F5 to reload the page.</p>

<p><strong>Note:</strong> Due to different browser settings, this event may now always work as exepcted.</p>

<script type='text/javascript'>

var myEvent = window.attachEvent || window.addEventListener;
var chkevent = window.attachEvent ? 'onbeforeunload' : 'beforeunload'; /// make IE7, IE8 compitable

        myEvent(chkevent, function(e) { // For >=IE7, Chrome, Firefox
            var confirmationMessage = 'Are you sure to leave the page?';  // a space
            (e || window.event).returnValue = confirmationMessage;
            return confirmationMessage;
        });

</script>

</body>

</html>


Demo:

http://vnlives.net/VN-Lives/Blog/Demo/Why jquery $(window).unload is not working.htm


Result - Kết quả:





Write: +Bui Ngoc Son





No comments:

Post a Comment