Reputation: 3262
I have this function
window.onbeforeunload = function () {
return "Are you sure?";
};
and I have a button that when the user presses it the window refreshes to update screen values and do some database calls. I added window.onbeforeunload=null;
in the beginning of the function to disable onbeforeunload but it kept being called.
Is there a way to either disable the onbeforeunload function in my button onclick function or make the window.onbeforeunload get called only on close window not on refresh?
Upvotes: 2
Views: 17723
Reputation:
Another approach is to use Cookies. set the cookie as a flag as when you want to refresh the page without having the onbeforeunload function call.
window.onbeforeunload = function (e) {
...
canceled = getCookie("canceled");
if (canceled == "false" || canceled == undefined)
{//do ur stuff here
}
...
}
and set your cookie to 5 secs so it expires right after you reload the page.
Upvotes: 1
Reputation: 146191
Following code should work (should be kept inside head tag between script tags)
window.onload=function(){
window.onbeforeunload = function(){
return "Are you sure?";
}
document.getElementById('refresh').onclick=function(){
window.onbeforeunload = null;
window.location.reload(); // replace with your code
}
}
Upvotes: 5