There are limitations to what the onbeforeunload
event can do in different browsers. Some browsers may not even support it, like Opera for example.
This event is primarily used to display a confirmation box asking if the user wants to leave the page or not. It cannot execute functions like alert
or confirm
, redirect the user, make AJAX calls, or perform other actions.
Instead, you can only return a string that will be displayed in a browser-generated alert confirming whether the user wants to leave or stay. Note that Firefox may not always show this string (bug# 588292).
var internalLink = false;
function pageUnload() {
if (!internalLink && location.protocol != 'http:') {
internalLink = true;
var s = 'Alert Message';
// You are limited in what you can do here
return s; // This message will appear in a confirm popup
}
}
window.onbeforeunload = pageUnload;
Browsers handle and trigger onbeforeunload
in specific ways, so caution should be exercised when using this event.
There is no definitive method to determine whether the user clicked "leave" or "stay". The common approach involves using the unload
event along with a setTimeout
, although it is considered hacky.
var internalLink = false,
stayTimeout, stayClicked;
function pageUnload() {
if(stayClicked){
return; // Prevent running multiple times
}
if (!internalLink && location.protocol != 'http:') {
internalLink = true;
stayClicked = true; // Mark event as executed once
setTimeout(stayOnPage, 1000);
var s = 'Alert Message';
return s; // This message will appear in a confirm popup
}
}
function stayOnPage(){
location.href= 'foo.com'; // Redirect if user chooses to stay
// Reset stayClicked if not redirecting
// stayClicked = false;
}
function leavePage(){
clearTimeout(stayTimeout); // Clear timeout on page leave
}
window.onbeforeunload = pageUnload;
window.unload = leavePage;
A better alternative is to attach events to <a>
tags, use custom confirm boxes, and proceed accordingly.
var a = document.getElementsByTagName('a');
for(var b in a){
a[b].addEventListener('click', function(e){
var c = confirm('Do you want to follow this link?');
if(c){
return true; // Allow user to leave
}
else{
e.preventDefault(); // Block link click
location.href= 'foo.com'; // Redirect if needed
}
});
}