Home >Web Front-end >JS Tutorial >How Can I Reliably Detect Browser Window/Tab Closure Without Triggering on Form Submissions?

How Can I Reliably Detect Browser Window/Tab Closure Without Triggering on Form Submissions?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-20 22:25:17511browse

How Can I Reliably Detect Browser Window/Tab Closure Without Triggering on Form Submissions?

Determining Browser Window/Tab Closure

Q: Capturing Browser Window/Tab Closure Event

I'd like to capture the browser window/tab close event, but the jQuery "beforeunload" event also triggers on form submissions. How can I limit the event to window closures?

A: Isolating Window Closure Event

While "beforeunload" detects any page departure, we can exclude form submissions and hyperlinks using the following code:

var inFormOrLink;
$('a').on('click', function() { inFormOrLink = true; });
$('form').on('submit', function() { inFormOrLink = true; });

$(window).on("beforeunload", function() { 
    return inFormOrLink ? "Do you really want to close?" : null; 
});

For jQuery versions < 1.7:

var inFormOrLink;
$('a').live('click', function() { inFormOrLink = true; });
$('form').bind('submit', function() { inFormOrLink = true; });

$(window).bind("beforeunload", function() { 
    return inFormOrLink ? "Do you really want to close?" : null; 
});

Note: This solution prevents the confirmation prompt if another event handler cancels the submit or navigation. To address this, record the time of submit/click events and check if "beforeunload" occurs more than a few seconds later.

The above is the detailed content of How Can I Reliably Detect Browser Window/Tab Closure Without Triggering on Form Submissions?. 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