Home > Web Front-end > JS Tutorial > How Can I Detect Browser Window Closure Without Intercepting Form Submissions?

How Can I Detect Browser Window Closure Without Intercepting Form Submissions?

Barbara Streisand
Release: 2024-12-13 22:40:14
Original
321 people have browsed it

How Can I Detect Browser Window Closure Without Intercepting Form Submissions?

Capturing Browser Window Close Event Without Form Submission Interception

To capture the browser window close event specifically, avoiding conflicts with form submission, jQuery's beforeunload event can be exploited with a slight modification.

The beforeunload event, as it stands, triggers for any action that causes the page to be abandoned. To restrict it to window close events alone, we employ the following approach:

The updated code for jQuery versions 1.7 and later:

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; 
})
Copy after login

For older versions of jQuery (prior to 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; 
})
Copy after login

The above is the detailed content of How Can I Detect Browser Window Closure Without Intercepting Form Submissions?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template