Reputation: 1372
I have the code below which asks for confirmation when a user tries to reload the page. It works fine
window.onbeforeunload = function(event) {
return confirm('Confirm refresh');
};
In another part of the code, I am redirecting it to the page using window.location.href
It returns a popup whether you want to leave the page. How can I avoid this popup when using window.location.href
?
window.location.href = window.location.href.split('#')[0];
Upvotes: 0
Views: 1104
Reputation: 1391
You could just set a variable to skip this behaviour :
let skipUnloadConfirm = false;
window.onbeforeunload = function(event) {
if(!skipUnloadConfirm) {
return confirm('Confirm refresh');
}
};
And then change value before setting href (function would replace direct window.location.href
assignement and could be reused)
function redirect(url) {
skipUnloadConfirm = true;
window.location.href = url;
}
Or, you can override window.onbeforeunload
before calling redirect
Upvotes: 2