Home >Web Front-end >JS Tutorial >How Can I Reliably Detect Browser Close Events in JavaScript?

How Can I Reliably Detect Browser Close Events in JavaScript?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-03 04:05:09839browse

How Can I Reliably Detect Browser Close Events in JavaScript?

How to Effectively Handle Browser Close Events

Detecting browser close events can be challenging, especially with methods like jQuery's onbeforeunload and onunload not always being reliable. This article provides a solution to detect window close, unload, or beforeunload events effectively.

Solution:

The following JavaScript code can be used to detect browser close events:

window.onbeforeunload = function (event) {
    var message = 'Important: Please click on \'Save\' button to leave this page.';
    if (typeof event == 'undefined') {
        event = window.event;
    }
    if (event) {
        event.returnValue = message;
    }
    return message;
};

$(function () {
    $("a").not('#lnkLogOut').click(function () {
        window.onbeforeunload = null;
    });
    $(".btn").click(function () {
        window.onbeforeunload = null;
});
});

Optional Implementation:

The second function in the code is optional. It prevents the prompt from displaying when clicking on specific elements, such as #lnkLogOut and .btn.

Note:

It's important to be aware that custom prompts may not work in Firefox. Refer to [this thread](link-to-thread) for more information.

The above is the detailed content of How Can I Reliably Detect Browser Close Events in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn