Make a GET/POST request inside 'onbeforeunload' function - javascript

I want to make a HTTP POST (or even GET is fine) request when the user leave the page.
I tried with 'onbeforeunload' 'unload' event listeners to watch when the users redirect to some other different page.
Is there any way I can check whether the user clicked on 'Leave' or 'Stay' button in default 'onbeforeunload' confirm box?
I want to call the function (make a request) only when he clicks the 'Leave' button.
How can I achieve this?

you can try
window.onunload
the function depends on browser
There is both window.onbeforeunload and window.onunload, which are used differently depending on the browser.Quote from here

onunload (or onbeforeunload) cannot redirect the user to another page. This is for security reasons.
If you want to show a prompt before the user leaves the page, use
onbeforeunload:
window.onbeforeunload = function(){
return 'Are you sure you want to leave?';
};
Or with jQuery:
$(window).bind('beforeunload', function(){
return 'Are you sure you want to leave?';
});
This will just ask the user if they want to leave the page or not, you cannot redirect them if they select to stay on the page. If they select to leave, the browser will go where they told it to go.
You can use onunload to do stuff before the page is unloaded, but you cannot redirect from there (Chrome 14+ blocks alerts inside onunload):
window.onunload = function() {
alert('Bye.');
}
Or with jQuery:
$(window).unload(function(){
alert('Bye.');
});

Well, this is what I did :
When user tries to leave the page - Call the API (which I wanted to call if user clicks on leave button) within onbeforeunload event listener.
If user clicks on leave button, he will be redirected to other page.
If user clicks on stay button, I have a timeout function inside onbeforeunload event listener which will be executed after certain amount of time (2 seconds) where user would stay on current page itself. [In this API I'm revoking the operations what was done by API which was called in 1st step]

Related

Handling Re-direct in Dirty Form

On my form, a user can modify it, i.e. make it dirty, and then click the Cancel button.
The Cancel button's onClick() behavior is to change window.location.
However, when I press the "Cancel" button, I notice that the window.location only changes if I click "OK" (IE8) or "Leave this Page" (FF or Chrome). But, if I click "Cancel" (IE8) or "Stay on this Page" (FF or Chrome), then the actual window.location does not change.
How does this work?
EDIT including code:
function (buttonPressed) { // called when Cancel button is pressed
window.location = ...;
}
As #マルちゃん だよ said, you can't force a redirect if the user doesn't allow it. It just won't happen. However, the question that needs to be asked is what your "Cancel" action does, and whether you actually need to use Javascript for it.
If you want the cancel button to reset the entire form, there are ways to do that, either
Using a button with type=reset, or
Using the form.reset function
Alternatively, if cancelling is meant to take the user to a different location, then while the words may say cancel, the button is actually submitting the form and relocating them. So, make the button a type=submit, capture the fact that the form was cancelled (maybe even store it so the user can return to it later), and redirect them server side to the right page. This has the added benefit that you can track how many users are cencelling, and working when Javascript is turned off or unavailable.
What you are asking for would be a major security breach. I'm afraid you will never be able to do that.
You can, however, have control over child windows the parent has opened. Say you opened a popup with a parent window, that same parent window can have a button to close the child. Never the main window.
As for the "Cancel" event on that confirmation dialog, you could always handle it:
window.onbeforeunload = function () {
if (confirm('Are you sure you want to leave this page?')) {
return; // allow user to exit without further annoying pop-ups
} else {
// Handle the Cancel event
// ...
return "Do you really, really want to Exit?"; // Make the browser ask for confirmation again
}
}
If the user does something to leave the page, then you can tell the browser to ask them if they are sure. You cannot silently prevent them. If the user wishes to leave the page, then they can do so (dodgy sites full of adverts and/or malware would love it to be otherwise, thankfully it isn't)

How does StackOverflow implement a pop-up box before you close the tab while you are writing an answer? [duplicate]

How can I ask the user Are you sure you want to leave the page?
Like for example if you click the back button while asking a question on Stackoverflow?
The easiest way to do this is to bind an event handler to the "unload" JavaScript event. jQuery makes this very easy to do with its .unload() event handler. In the method you bind you can check to see if any the page's form fields have text input. Assuming they do pop an alert notifying the user they'll lose any unsaved data if they navigate from the page.
This method will fire an alert whenever the user navigates away from the page for any reason.
$(window).bind('beforeunload', function() {
alert('Handler for .beforeunload() called.');
});
That's obviously not very user friendly but a couple of quick modifications can make it workable to your question.

How can I ask a web user for confirmation if he really wants to leave the page?

How can I ask the user Are you sure you want to leave the page?
Like for example if you click the back button while asking a question on Stackoverflow?
The easiest way to do this is to bind an event handler to the "unload" JavaScript event. jQuery makes this very easy to do with its .unload() event handler. In the method you bind you can check to see if any the page's form fields have text input. Assuming they do pop an alert notifying the user they'll lose any unsaved data if they navigate from the page.
This method will fire an alert whenever the user navigates away from the page for any reason.
$(window).bind('beforeunload', function() {
alert('Handler for .beforeunload() called.');
});
That's obviously not very user friendly but a couple of quick modifications can make it workable to your question.

How do i handle ajax and closing pages

If the user happens to have a delay in connecting to my site, the ajax hasnt timed out and the user decides to close the window. The ajax query will be terminated? Is there a way i can say still processing are you close you want to leave this page? (bonus if it will close once ajax was successful). How do i do this?
I am not sure if this is the same thing (maybe its built into firefox?) but when i closed this page it said
Are you sure you want to navigate away from this page?
You have started writing or editing a post.
Press OK to continue, or Cancel to stay on the current page.
I am positive i seen this other places. How do i make this appear when the user isnt submitting ajax and is in the middle of a post?
You can use the window.onbeforeunload event to handle this. Set a variable to false at the start of the ajax request. And in the callback function set its value to true, and in the window.onbeforeunload event check that variable and display suitable message.
Note
This will fire when you refresh your page also.
You can implement the onbeforeunload handler in js:
window.onbeforeunload = function()
{
if (showMessage)
{
return trye
}
else
{
return;
}
}

Display a confirm message

Want to display a "confirm" message in my asp.net application, when the window closes, but when the Cancel button is pressed, the page closes, the event is not Canceled.
I tried a different approach: I use
event.returnValue = "Message";
This approach works (when cancel is pressed, page does not close), but I get the "Message" that I specify plus some other message; "Click Accept or Cancel to cancel" or something similar.
How can I create a message on the client side that only displays the text that I specify?
You can't. The confirm message shown when a script attempts to prevent browser close/leaving the page is in part defined by the browser. You can only define part of the message.
This can't be done as a confirm message is shown when script attempts to change the closing behavior of the page by the browser
window.onbeforeunload = function() {
if(!confirm("Well?"))
return "PLEASE STICK AROUND!";
}
Note: onbeforeunload fires when the document is unloaded, not the window. So every redirect will fire the event. I'm afraid this is the best you can do.

Categories