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!