Alert when page closing, do something when page won't closed - javascript

Found a working script on the internet, except that I can't change the message for FF. Which would be great. (Works for Chrome)
window.onbeforeunload = function(e) {
if(!e) e = window.event;
e.cancelBubble = true;
e.returnValue = 'You sure you want to leave?';
if(e.stopPropagation) {
e.stopPropagation();
e.preventDefault();
}
};
What ever, this works great. But I wanna do something when the user clicks on abort to keep visiting the page.
How I could do that?

You could use a timed function to do something if user decides to stay on page. The confirmbox shown by onbeforeunload is blocking the execution untill user clicks either OK or Cancel. If Cancel will be clicked, the timed function will be executed, otherwise the page is closed, and the timed function will never be executed.
The code would be something like this:
window.addEventListener('beforeunload', function (e) {
e.preventDefault();
e.returnValue = 'Do you want to leave the page?';
setTimeout(function () { // Timeout to wait for user response
setTimeout(function () { // Timeout to wait onunload, if not fired then this will be executed
console.log('User stayed on the page.');
}, 50)}, 50);
return 'Do you want to leave the page?';
});
A working demo at jsFiddle.
You can't show a message in the confirmbox in FF for the reason explained in the accepted answer in the post RGraham has linked in their comment.

Related

Detecting if beforeunload event was cancelled by an unrelated function

I have a simple function to show a spinner overlay while a new page request is being made.
$(window).on("beforeunload", function() {
$('#nav-spinner').show();
});
This works perfectly.. but, it is used on a complex WordPress site and there are other (third party) components that also use this event to sometimes cancel the navigation (for instance, a confirmation when navigating away from a partially filled form).
Is there any way to determine if another function cancelled the page unload so I can remove my overlay immediately when they are remaining on the page.
I would like to do this when an actual navigation is cancelled - using a timer to remove the overlay will result in either the overlay being hidden prematurely or remaining for longer than it should.
Test Case that shows the problem
So the following code shows what you have currently. I am setting the background red since it is a minimum amount of code.
window.addEventListener("beforeunload", function(event) {
document.body.classList.add("red");
});
// 3rd party code that is showing the "are you sure"
window.addEventListener("beforeunload", function(event) {
event.preventDefault();
event.returnValue = 'I am 3rd party code';
});
.red {
background-color: red;
}
<form>
<button>Click Me then click "Cancel"</button>
</form>
Solving the problem
So now that we have the test case for what is wrong. The background should NOT remain red when the user clicks cancel. So how can we detect it? Well there is NO events that tells you what the user did.
So the only thing you can do would be to add a timer to remove what you added when the user cancels it. So if they click cancel, the timer runs and removes it.
But how do we keep it there if they do not cancel it? We use unload to kill the timeout that hides it. So remove the timeout and it will not fire.
var timer
// update the page as page exits
window.addEventListener("beforeunload", function(event) {
document.body.classList.add("red");
// if this timer runs, it means beforeunload was cancelled
timer = window.setTimeout( function () {
document.body.classList.remove("red");
}, 50);
});
// remove the timer when the pages finally exits so the class is not removed.
window.addEventListener("unload", function(event) {
window.clearTimeout(timer)
})
// 3rd party code that is showing the "are you sure"
window.addEventListener("beforeunload", function(event) {
event.preventDefault();
event.returnValue = 'I am 3rd party code';
});
.red {
background-color: red;
}
<form>
<button>Click Me then click "Cancel"</button>
</form>
You may have to play with the timeout millisecond values. The flash of content for showing could be lessened with a transition, but hopefully the browser does not kill that unload.

Can we detect browsers refresh and back button events?

Anybody know how to detect browsers refresh and back button events in firefox using jquery or javascript.
For back button:
window.addEventListener('popstate', function (event) {
//Your code here
});
For Refresh:
window.onbeforeunload = function () {
// Your code here
}
You can try WindowEventHandlers.onbeforeunload:
window.onbeforeunload = function(e) {
};
and
$(window).unload(function() {
//
});
Also check Browser Back Button Detection:
I have made a very reusable javascript class, that can be simply
dropped into your web page, and when the user clicks back, it will
call a function. The default function on this call is a javascript
alert “Back Button Clicked”.
To replace this functionality, you simply need to override the OnBack
function. This can be done by using the code below.
<script type="text/javascript">
bajb_backdetect.OnBack = function()
{
alert('You clicked it!');
}
</script>
This will now replace the “Back Button Clicked” alert with a “You
clicked it!’” alert.
Check this page: Manipulating the browser history
You can probably get something working with using history.pushState and window.onpopstate
You can use the following events:
window.onpopstate for back button press.
window.onpopstate = (e) => {
// your logic goes here
};
window.onbeforeunload for refresh or tab close.
window.onbeforeunload = (e) => {
// your logic here
e.preventDefault();
e.returnValue = 'There are unsaved changes. Sure you want to leave?';
};

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

boxy.confirm don't wait for confirm

In case the close (X) is pressed, Boxy doesn't wait for a confirmation. Below is an example describing my problem:
$('form .close').click(function(event) {
event.stopPropagation();
Boxy.confirm("Are you sure ?", function() {
alert('ok');
});
return false;
});
However, when the OK button is clicked, everything works as expected.
Why does this not work as expected in case the (X) is pressed?
Please see this example that I made for you: http://jsfiddle.net/972ak/
$('form .close').click(function(event) {
Boxy.confirm("Are you sure ?", function() {
alert('ok');
});
return false;
});
Boxy documentation says:
Boxy.confirm(message, callback, options)
Displays a modal, non-closeable dialog displaying a message with OK and Cancel buttons. Callback will only be fired if user selects OK.
http://onehackoranother.com/projects/jquery/boxy/
As I have already mentioned in my comment Boxy.confirm is async unlike native confirm. Your code will continue its execution without waiting for user to click OK or Cancel. That is why you need to perform the actual action inside confirm callback.
Consider the following code.
$('form .close').click(function(e){
var form = $(this).closest('form');
Boxy.confirm('Are you sure?', function() {
form.remove(); //remove it only if user confirmed.
});
form.append('<p>Close was clicked.</p>');
})
This code will append message every time user clicks close link. But the form will be actually removed only if user confirmed the action.
http://jsfiddle.net/tarabyte/972ak/4/

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