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
Converting an Object to a String
What's the Right Way to Decode a String That Has Special HTML Entities in It
How to Dynamically Modify <Select> in Materialize CSS Framework
Generate Dynamic CSS Based on Variables Angular
Null-Safe Property Access (And Conditional Assignment) in Es6/2015
How to Set File Input Value When Dropping File on Page
Is "Clear" a Reserved Word in JavaScript
Google Seo and Hidden Elements
Changing Background Based on Time of Day (Using JavaScript)
JavaScript - Generating Combinations from N Arrays With M Elements
CSS Hover VS. JavaScript Mouseover
Get the Scale Value of an Element
Count Down Timer with Circular Progress Bar
.Trim() in JavaScript Not Working in Ie
How to Delete an Item from State Array