I need to do something when the browser is closing, so first I need to know that it closes. What I found was:
<script>
var closing = true;
$(function () {
$("a,button[type=submit]").click(function()
{
closing=false;
});
$(window).on("unload",function(){
if (closing){...}
});
});
</script>
It works good/nice/etc but there is one "catch": page reload... When the page is reloaded, it's not any click, so it's treated as "closing"... Is there such an easy way to catch the reload (as for the "click" written above)?
Try to use navigation object property, there you can find the information page is reloaded(value is equal to 1) or not:
<script>
var closing = true;
var performance = window.performance;
$(function () {
if((performance.navigation && performance.navigation.type === 1) ||
performance
.getEntriesByType('navigation')
.map((nav) => nav.type)
.includes('reload')){
closing = false;
console.log("reloaded");
}
$("a,button[type=submit]").click(function()
{
closing = false;
});
$(window).on("unload",function(){
if (closing){
console.log("closing");
}
});
});
</script>