Run JavaScript Code on Window Close or Page Refresh

Run JavaScript code on window close or page refresh?

Ok, I found a working solution for this, it consists of using the beforeunload event and then making the handler return null. This executes the wanted code without a confirmation box popping-up. It goes something like this:

window.onbeforeunload = closingCode;
function closingCode(){
// do something...
return null;
}

Refresh page and run function after - JavaScript

You need to call myFunction() when the page is loaded.

window.onload = myFunction;

If you only want to run it when the page is reloaded, not when it's loaded for the first time, you could use sessionStorage to pass this information.

window.onload = function() {
var reloading = sessionStorage.getItem("reloading");
if (reloading) {
sessionStorage.removeItem("reloading");
myFunction();
}
}

function reloadP() {
sessionStorage.setItem("reloading", "true");
document.location.reload();
}

DEMO

How do I run Javascript code only if the user actually closes the tab?

As the name suggests, this event happens before the page is unloaded, and allows the user to cancel the unload.

Use an unload event listener to detect when the page is actually being unloaded. If you have both event listeners, this will only run if the user selected Leave.

How to run a method when the window closes in JavaScript

Not possible anymore.

Newer browsers doesn't support it anymore.



Related Topics



Leave a reply



Submit