I want to track page refresh or tab closing via the beforeunload event, but I don’t quite understand how it works? I can’t track the user’s cancellation and apply the DOM change before the pop-up window, maybe this is not possible?
I want to do the following. When trying to reload the page or leave it, I call beforeunload with the functions e.preventDefault() and e.returnValue = false, I want to blur the page content, and when the user cancels the action (i.e. he remains on the page further) remove the blur. Is this even possible to do?
For example, the confirm() function can return true or false, and I can track this, so what should I do with beforeunload?
In this example, the styles are applied after “Cancel” the page update in the dialog box. Is it possible to somehow change the styles BEFORE the dialog box appears, or is it impossible to do this? And is it possible to track the cancellation of the update, i.e. pressing the “Cancel” button in the dialog box, to remove these styles.
The example in the link in the comment gives a policy error.
UPD:
Here’s what I tried to do:
$(window).on('beforeunload', function(e) {
if ($('#switch').is(':checked')) {
e.preventDefault()
e.returnValue = false
$('.box').css({
'filter': 'blur(10px)',
'-webkit-filter': 'blur(10px)',
'-moz-filter': 'blur(10px)',
'-o-filter': 'blur(10px)',
'-ms-filter': 'blur(10px)'
});
}
})
<label><input type="checkbox" id="switch" checked> Switch</lable>
<button onclick="location.reload()">Reload Page</button>
<h2 class="box">Page Content</h2>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>