Stopping the user from navigating away using `window.onbeforeunload` - javascript

I am trying to display an alert when the user clicks the back, forward or refresh browser buttons, but I am not getting the desired output...
<script type="text/javascript">
$(document).ready(displayAlert());
function displayAlert() {
window.onbeforeunload = function () {
return "Are you sure want to LOGOUT the session ?";
};
}
</script>

WindowEventHandlers.onunload The unload event is raised when the window is unloading its content and resources. The resources removal is processed after the unload event occurs.
window.onunload = funcRef;
WindowEventHandlers.onbeforeunload An event that fires when a window is about to unload its resources. The document is still visible and the event is still cancelable.
window.onbeforeunload = function(e) {
return 'Dialog text here.';
};
IE has issues with onload event and Opera has with onbeforeunload. So to reach to a solution which would handle both the situations I came across user3253009 answer
/*Code Start*/
var myEvent = window.attachEvent || window.addEventListener;
var chkevent = window.attachEvent ? 'onbeforeunload' : 'beforeunload'; /// make IE7, IE8 compitable
myEvent(chkevent, function(e) { // For >=IE7, Chrome, Firefox
var confirmationMessage = 'Cookies for you.. If you stay back!!?'; // a space
(e || window.event).returnValue = confirmationMessage;
return confirmationMessage;
});
/*Code End*/
Gist. Hope it helps!
Update
If you want to show a Bootstrap Modal when user is navigating away from you page,then you can try something like below:
window.onbeforeunload = function(event) {
event.preventDefault();
$('#cancel_modal').modal('show');
};

Related

Some way to detect close tab/browser for all browsers?

There are some way of detecting a close event from tab/browser without close when i click in other links in page or forms and valid for all browser, i tested "beforeunload" and other replies about this topic here and not working, i am testing in Firefox and Chrome
This is not working :
window.onbeforeunload = function (event) {
var message = 'Important: Please click on \'Save\' button to leave this page.';
if (typeof event == 'undefined') {
event = window.event;
}
if (event) {
event.returnValue = message;
}
return message;
};
Same when i close the tab or the browser is doing nothing; but yes when i click a link

Remove page refresh browser popup

I added page beforeunload and unload functions as follows:
window.onunload = function (e)
{
//mycode1
return '';
};
window.onbeforeunload = function(e){
//mycode2
return '';
}
and they are getting called after browser confirmation popup occurs. But now I want to unbind these functions. I tried
window.onunload = null;
window.onbeforeunload = null;
But seems like they are not working and still browser refresh confirmation popup appears.

How to prevent navigation by browser buttons but not by links?

I want warn users if they leave the page by closing the browser or using the history buttons of the browser using the following javascript:
window.onbeforeunload = function(e) {
return 'Ask user a page leaving question here';
};
But my links and buttons on my website should work regardless of this. How can I achieve that?
The first way that comes to mind is to set a variable that tells you whether a link was clicked:
var linked = false;
window.onbeforeunload = function(e) {
if (!linked)
return 'Ask user a page leaving question here';
};
document.addEventListener('click', function(e) {
if (e.target.tagName === "A")
linked = true;
}, false);
That is, set a click event handler at the document level, that tests whether the clicked element was an anchor (or whatever else you want to allow) and if so sets the variable. (Obviously this assumes that you don't have other anchor element click handlers at a lower level that stop event propagation.)
var linkClicked = false;
window.onbeforeunload = function(e) {
if (!linkClicked){
linkClicked = false;
return 'Ask user a page leaving question here';
}
};
$(document).ready(function(){
$('a').click(function(e){
linkClicked = true;
});
});
Obviously this relies on JQuery to add the event handler to all links, but you could attach the handler with any other method, including adding onclick="linkClicked=true;" to every link on the page if you really have to.
Edit:
Just want to point out that if the user clicks a link that doesn't redirect them (e.g. a hashtag link to somewhere else on the page, or something that returns false / prevents the default action being executed) then this will set linkClicked to true and subsequently any browser based navigation won't be caught.
If you want to catch this, I would advise setting a timeout on the link click like so:
$(document).ready(function(){
$('a').click(function(e){
linkClicked = true;
setTimeout(function(){
linkClicked = false;
}, 500);
});
});
This will allow half a second for the window unload event to trigger before resetting the flag so that future navigation events are caught correctly. This still isn't perfect, but it probably doesn't need to be.
You can use the window.onbeforeunload event.
var check= false;
window.onbeforeunload = function () {
if (!check) {
return "Are you sure you want to leave this page?"
}
}
function CheckBackButton() {
check= true;
}
referenceElement.addEventListener('onClick', CheckBackButton(), false);
Us a confirmation prompt no?
like this? Intercept page exit event
window.onbeforeunload = function (e) {
var message = "Your confirmation message goes here.",
e = e || window.event;
// For IE and Firefox
if (e) {
e.returnValue = message;
}
// For Safari
return message;
};
How to show the “Are you sure you want to navigate away from this page?” when changes committed? this may solve your problem How

Execute Javascript function before browser reloads/closes browser/exits page?

Is there a way to execute a function before a user chooses to reload/close browser/exit page?
I need this for an "online/offline" status function i am trying to write. I want to detect whether the user is still on the page or not.
Any ideas? :)
Maybe there is a better approach to this?
Inline function:
window.onbeforeunload = function(evt) {
// Cancel the event (if necessary)
evt.preventDefault();
// Google Chrome requires returnValue to be set
evt.returnValue = '';
return null;
};
or via an event listener (recommended):
window.addEventListener("beforeunload", function(evt) {
// Cancel the event (if necessary)
evt.preventDefault();
// Google Chrome requires returnValue to be set
evt.returnValue = '';
return null;
});
or if you have jQuery:
$(window).on("beforeunload", function(evt) {
// Cancel the event (if necessary)
evt.preventDefault();
// Google Chrome requires returnValue to be set
evt.returnValue = '';
return null;
});
Notes:
When this event returns a non-void value, the user is prompted to
confirm the page unload. In most browsers, the return value of the
event is displayed in this dialog.
Since 25 May 2011, the HTML5 specification states that calls to
window.showModalDialog(), window.alert(), window.confirm() and
window.prompt() methods may be ignored during this event.
See documentation at https://developer.mozilla.org/en-US/docs/Web/API/WindowEventHandlers/onbeforeunload
Use window.onbeforeunload, it is triggered when user leaves your page :http://geekswithblogs.net/hmloo/archive/2012/02/15/use-window.onbeforeunload-event-to-stop-browser-from-closing-or-disable.aspx
Try this:
$( window ).unload(function() {
alert( "Handler for .unload() called." );
});
OR this if you want conformation alert
<script>
window.onbeforeunload = function(e) {
return 'Your dialog message';
};
</script>

I want to call function on window unload

I am trying to display confirmation box using window.confirm on window unload event.
If a user clicks on the OK button on confirmation box then I want to call one function and if user clicks the CANCEL button then window should be get closed.
My code is:
<script>
function confirmit(){
var result=window.confirm("Are you sure?");
if(result) {
// close all child windows
} else{
// window should not get close
}
}
</script>
<body onunload='confirmit();' >
But the problem is if I click on CANCEL button, window is getting closed.
Please help me.
You can't prevent unload to stop the page from unloading. You need to bind to onbeforeunload instead. You should just return the string you want to display to the user from the event handler (note that in some browsers the string may not be displayed)
<script type="text/javascript">
window.onbeforeunload = function(e){
var msg = 'Are you sure?';
e = e || window.event;
if(e)
e.returnValue = msg;
return msg;
}
</script>
More info here
JSFiddle Example here
change your code to this to make it work cross-browser:
<script>
window.onbeforeunload = function (e) {
e = e || window.event;
// For IE and Firefox prior to version 4
if (e) {
e.returnValue = 'Do you really want to exit?';
}
// For Safari
return 'Do you really want to exit?';
};
</script>
<body>
...
note that this is using the onbeforeunload-event (more information / view an example) where the return-value has to be the message that should be shown to the user.
i don't know if you'll have a chance to react on the confirmation to do something after that (closing child-windows for example), but i don't think so.

Categories