Home > Web Front-end > JS Tutorial > How Can I Capture Browser Window Close Events Without Triggering on Form Submissions or Hyperlinks?

How Can I Capture Browser Window Close Events Without Triggering on Form Submissions or Hyperlinks?

Susan Sarandon
Release: 2024-12-07 12:56:14
Original
543 people have browsed it

How Can I Capture Browser Window Close Events Without Triggering on Form Submissions or Hyperlinks?

Capturing Browser Window Close Event While Excluding Form Submissions and Hyperlinks

The beforeunload event in jQuery is designed to detect when a user leaves a page. However, this event also triggers upon form submission, which may not be desirable in certain scenarios. This article explores an approach to exclude form submissions and hyperlinks (except from other frames) from the beforeunload event.

To achieve this, we first initialize a variable inFormOrLink to false. When a user clicks on a hyperlink or submits a form, we set inFormOrLink to true.

Within the beforeunload event handler, we check the value of inFormOrLink. If it's true, we prompt the user for confirmation with the message "Do you really want to close?" Conversely, if inFormOrLink is false, we return null to suppress the confirmation prompt.

Here's a revised code snippet for jQuery versions 1.7 and above:

var inFormOrLink = false;
$('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 jQuery versions below 1.7, use the following code:

var inFormOrLink = false;
$('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

This approach effectively captures the browser window close event while excluding form submissions and hyperlinks (except from other frames).

The above is the detailed content of How Can I Capture Browser Window Close Events Without Triggering on Form Submissions or Hyperlinks?. 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