Home >Web Front-end >JS Tutorial >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:
In the beforeunload event handler, we check the value of inFormOrLink.
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; })
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; })
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!