How do i handle ajax and closing pages - javascript

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;
}
}

Related

Make a GET/POST request inside 'onbeforeunload' function

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]

How to wait until jquery animation is finished using the onbeforeunload event?

It looks like a basic problem, but I simply can not solve this. I am using an animation to smooth the navigation between pages. The window.onbeforeunload event looks good to fire the animation, but jquery do the animation on a new thread. Is there any way to wait until the animation is finished? I tried using the delay() and setTimeout() jquery functions but they obviously not stopped the function. When I add a loop at the end to wait, the window is not refreshing so the animation not even shown.
My code (jsfiddle):
window.onbeforeunload = function (e) {
$('#loader-sheet').fadeIn(500);
}
From MDN:
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.
onBeforeUnload is used to prompt a user, not to perform actions (like ajax, animations, or otherwise)
https://developer.mozilla.org/en-US/docs/Web/API/Window.onbeforeunload
There's no API to accomplish what you are looking to do. If a user is leaving, the only thing the browser will let you do is prompt them and ask them if they are sure they want to leave. You cannot prevent them (or delay them while still maintaining control of the UI, or anything that uses a JavaScript API) from navigating away from your page.
You cannot prevent the page from changing - you can only present some text as confirmation (e.g. "You have an unsaved draft, are you sure you would like to leave?").
This is by design - imagine if every annoying ad popup was allowed to prevent you from exiting the page by entering a 200-second animation.
However, you might still be able to do something, depending on exactly why the page is changing. For instance, if they are clicking a link on your page (not using back/forward buttons), then you could override the click handler for each of those links, like:
$('a[href]').on('click', function () {
if (/* link would change page */) {
performPageTransition(this.getAttribute('href'));
return false;
}
});
function performPageTransition(newUrl) {
$('#loaderSheet').fadeIn(500, function () {
// Animation complete - move to new URL
window.location = newUrl;
});
}
So instead of following the link instantly, you intercept the click event, and then move the page manually yourself later.
However, I would also consider whether it's possible to load the new page content via AJAX.

Chrome/Safari not calling unload in some cases

Have been stuck with this issue for a few days now, and really need, and would appreciate some help. My requirement is that I want to make a server side callback to clear off some objects when the user navigates away from our page, without clicking logout. For business reasons, our ASP.NET session timeout has to be set to a very high value. Further, I do not want to popup a alert/dialog to force the user to return to the page and click Logoff.
The solution I have arrived at thus far is to make a AJAX callback by embedding this javascript in the page.
window.onunload = pageleave;
function pageleave() {
alert('test');
PageMethods.CheckLogout('abc','xyz',OnSucceed,OnFail);
}
Here is the problem though :
For IE and Firefox, the unload fires, the alert is seen, and I see the callback on my C# side in all the cases I desire
a) User closes browser
b) User types in a new URL in the address bar
c) User clicks on a link causing page to reload
For Chrome and Safari, cases a and b work fine. However, when the user clicks on a link, which causes my aspx page to reload, my C# side code is not invoked. The javasacript alert is fired though.
I am trying to see how I can get Chrome/Safari to behave like IE/Firefox. Is this even a possibility?
Thanks in advance for the help,
Rajesh.
Use the beforeunload event instead of the unload event.
Also, use a synchronous AJAX request, not an asynchronous one, so that the request is completed before your beforeunload function exits.
I'm not sure how you would do a synchronous AJAX request using your JavaScript framework. In jQuery, it would look like this:
window.onbeforeunload = function() {
jQuery.ajax({
url: '/page/to/load',
async: false
});
};
In case anyone comes across this in the future, I couldn't use window.onbeforeunload as it was firing too early. Instead, I found window.onpagehide as a suitable workaround.
e.g.
window.onpagehide = function() {
// some code here.
};

How to JS function to catching Reload Button

How can i write JS function to catching a Reload Button (on browser) then i pressed on.
I want to pop up alert something like that.
etc. -> and back button too.
Thank you.
You just can't.
The only solution is to use window.onbeforeunload to catch when user leaves page - reloads or uses back.
You can't detect these directly, you can use onbeforeunload to handle any unloading, including closing the browser, for example:
window.onbeforeunload = function() { return "Are you sure?"; };
But you can't detect what caused it, e.g. closing would as well, so would going forward in history.

JavaScript To Get An Alert To Redirect When Closing The Browser Window

I'm trying to get this JavaScript to work properly. My intention is, when a user is trying to close the site page to get an alert saying "stay on current page or close" If they hit 'ok' I want it to close, if they hit 'cancel' i want it to redirect to another page. The problem is, when they try to go to another page on the same site, it gives them that popup. I want it to show only when closing, not when leaving the page to another page. I'm not sure if that's possible, I do appreciate your help and comments.
window.onbeforeunload = fget;
function yPop(url) {
var found = 1;
window.onbeforeunload = '';
window.location = url;
return false;
}
function fget() {
alert("Thank you for visiting our website, you are welcome any time! \n\n");
window.location = "http://NewLink.com";
return "\n________________________\n\n PRESS 'CANCEL' To Stay On The Current Page \n\n________________________\n";
}
The problem is, when they try to go to another page on the same site, it gives them that popup. I want it to show only when closing
Don't do this.
You can't detect closing only, but you can tell the difference between leaving by clicking on an internal link and other kinds of leaving, including external links, back button, closing and choosing/typing a new URL. In a script after the page has loaded, set the onbeforeunload event, then scan over all the document.links and test their .host against the current location.host. If they match, it's an internal link. In this case add an onclick event to them that removes the onbeforeunload event before returning true, allowing the link to operate normally without a warning.
Seriously, don't do this. It is incredibly irritating, arrogant and useless. Webmasters who employ leaving-pester scripts are condemned to the the fourth circle of internet hell, where they must spend the rest of eternity making stylesheets work on Netscape 4 using only ed, a worn toothbrush and a < layer>-tag.
you should use the window onbeforeunload Event.
http://msdn.microsoft.com/en-us/library/ms536907(VS.85).aspx
https://developer.mozilla.org/en/DOM/window.onbeforeunload
for jquery users :
$(window).unload( function () { alert("Bye now!"); } );
You may want to consider building a "You're about to leave this site" page instead.
The idea is that you wrap URLs on the page that aren't on your site to point to that page, letting the visitor know they're about to leave, and giving them a chance to go back, or proceed.
It's gentler than an unexpected modal dialog, it lets you format your messaging better, and it ultimately gives your users the exact same choice.

Categories