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; });
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; });
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!