Below is my code to detect and stop the browser's back button in iPad browsers.
$(window).bind("pagehide", function(e) {
})
How can I stop the page going back on browsers' back button click in iPad browsers?
You can use the onbeforeunload event that triggers when a user is leaving your page, whether it's by hitting the back button, entering a new URL or closing the browser.
Here is an example:
window.onbeforeunload = function(){
return 'You are leaving!?';
}
And here is the result on Chrome:
This event seems to be inconsistent across browsers as some will not support it, some will execute whatever function you pass it, and some will reject the function if it doesn't return a string to put in the confirmation box.
As commenter Alex Wayne stated, think twice about this. It can really create a negative impact on your site or webapp to alter the native behaviour of the back button.
Related
window.onbeforeunload = goodbye;
I currently use the code above to detect the onbeforeunload event, but I'm wondering if there is a way to use the event object that was passed in to determine if the event was fired due to the back button being pressed or if it was from the user attempting to reload the page.
There is no life or death scenario here as Chrome (possibly others) tailors the text of the button.
I'd simply like to the tailor the message that I display...and it's bugging me that I can't find it when looking through the object in Chrome.
Long story is short - I am trying to submit a certain form when user closes the window, or is not responding for 20min.
The second I've done using this code:
timeOut = setTimeout(function () {
submitThisForm(document.forms.sendDealerInfo);
console.log("Timed out...");
}, 600000);
For the first one I've tried with this code:
window.onbeforeunload = function() {
submitThisForm(document.forms.sendDealerInfo);
clearTimeout(timeOut);
return null;
}
Unfortunately window.onbeforeunload event won't trigger in all browsers (in Chrome and Opera for example).
I also tried: $(window).unload(function () {... and window.addEventListener("beforeunload", function (event) {...
But same story - they won't work in all browsers.
Is there a way to accomplish what I am trying to do some other way? Perhaps with sessions?
As Suman says, onBeforeUnload is supported in all the major browsers. But most, if not all, the browsers will not let you do anything within that event beyond returning a string for the "Are you sure you want to leave this page?" dialog.
Then with onUnload you're attempting to submit a form after the page has already been unloaded, and navigation is already happening. It would be a very odd user experience to be navigating away then be redirected somewhere else.
Trying to submit a form when the window is closed isn't a very safe method. The web browser could crash, the user could force close it, the internet connection could be interrupted, among other things. I think your best bet would be to submit the form every so often. Possibly detecting an idle timeout of a few seconds, then submitting your form?
window.onbeforeunload is works in all major browsers, Like it is supported from Chrome 1 and Opera 12
Browser Compability
I want to show a message whenever you are leaving the page (not an annoying alert, just some html telling you to wait), in thinking about it I'm facing certain difficulties:
when the user presses Stop in the
browser, cancelling the navigate-away
action, I'd like the message to go
away.
whenever any link is clicked, the message should appear.
it shouldn't capture when the clicked link just opens another tab ( ignore _blank target )
that being said, firing the event is pretty simple, with just something like
$(document).unload(function()
{
// display message
});
the problem being that if the user cancels, the message wouldn't go away.
a possible fix would be:
$(window).unload(function()
{
// display message
setTimeout(function()
{
// hide message
},5000);
});
but I wanted to know if there was a cleaner way, that just when the user cancels the navigation (or it fails for any other reason), I can hide the message.
Edit #2:
I just noticed that with the above code, in FF the message isn't displayed until the page is left, at which point if the user presses Stop, he will receive about:blank. If he presses Stop before that, then the message is never displayed. Which is exactly what I wanted.
In internet explorer the message is never displayed, I'm assuming that's because IE handles stuff differently. I wonder what happens in chrome?
As to the first point:
when the user presses Stop in the browser, cancelling the navigate-away action, I'd like the message to go away.
I had the same question a while back, and the resounding response - also backed by my subsequent research - was that this is impossible. Once you start a request for a new page, it's impossible to reliably "come back" from it programmatically. A timeout may indeed be the only way to go.
The two other points, though, should be relatively straightforward: Walk through every link (e.g. using jQuery), and add a click event that opens the confirmation window, and returns false so that the original href isn't opened. It should also be relatively easy to do this for internal links only (check for the target property, if it's _blank, leave the link alone.)
It may become tough to deal with links that already have click events, though, and other events leading to a different page like form submissions.
Here is a solution that works in all browsers. It uses the document.readyState attribute which works in all browsers except early versions FireFox (works in version 3.6.8). If the browser supports the readyState attribute it will check if the readyState is load (browser is going to another page) or is complete (or something else indicating that the page is not going anywhere). If the browser does not support the readyState then it will default to your solution.
(function(){
var hideMessage=document.readyState?function(){
setTimeout(function(){
if(document.readyState=='loading'){
hideMessage();
}else{
//hide message
}
},500);
}:function(){
// hide message
}
function displayMessage(){
// display message
}
window.onbeforeunload=function(){
displayMessage();
setTimeout(hideMessage,document.readyState?10:5000);
};
}());
If the user refreshes the page in question it will add another record to the database, so I want to warn the user through an alert box if they really want to refresh the page and if they click ok then the page should be refreshed otherwise if they click cancel it won't be.
How to make this type of alert box appear when the browser's refresh button is clicked in a way that is cross browser compatible?
You can do it like this:
window.onbeforeunload = function() {
return "Data will be lost if you leave the page, are you sure?";
};
This would show a prompt to the user allowing them to cancel. It's not refresh specific, but for your purposes (like editing a question on SO) that doesn't seem to matter, it's loss of info no matter where you're leaving to.
There isn't a way to tie it to just the refresh action, but you may want to look into window.onbeforeunload. This will allow you to run a function that returns a string just before the page is unloaded. If this string is not empty, then a popup confirmation dialog, containing this string and some other boilerplate text provided from the browser.
For example:
window.onbeforeunload = function () {
if (someConditionThatIndicatesIShouldConfirm) {
return "If you reload this page, your previous action will be repeated";
} else {
//Don't return anything
}
}
Also, if the current page was loaded via a POST operation, then the browser should already display a confirmation box when the user tries to refresh it. As a general rule, any action that changes the state of the data on the server should be done through a POST request, rather than a GET.
All the answers are quite old, as of today 2020, according to HTML specification, you can do it this way.
Important Note: Custom text is not supported in most of the browsers now. (it was supported in older browsers).
https://developer.mozilla.org/en-US/docs/Web/API/WindowEventHandlers/onbeforeunload
window.addEventListener('beforeunload', function (e) {
// Cancel the event
e.preventDefault(); // If you prevent default behavior in Mozilla Firefox prompt will always be shown
// Chrome requires returnValue to be set
e.returnValue = '';
});
There are two possible ways forward with this, both quite different.
One way would be to have an event handler bound to onbeforeunload event so that you can detect when the user is browsing away from the current page. If my memory serves me correctly however, onbeforeunload is not consistent across browsers (I don't think Opera responds to it IIRC, but have no way to currently test). Of course, this solution fails if the user turns off JavaScript.
The second and more robust way would be to implement the Post Redirect Get pattern which when used, prevents the data from being posted again when a user refreshes the page.
This is not possible. The best you can do is use the onbeforeunload event but that will fire on any event leaving the current page. It is not possible to target the refresh button specifically.
See e.g. this question on onbeforeunload
It might be better though to build a duplicate check into your database. That would catch accidental submissions using the "back" button as well.
An alternative would be using a random one-time token that gets built into the form. If two operations are attempted using the same token, you would stop it.
Quoting from official Mozilla site here, It is no longer supported to supply a custom message.
When this event returns (or sets the returnValue property to) a value other than null or undefined, the user will be prompted to confirm the page unload. In older browsers, the return value of the event is displayed in this dialog. Starting with Firefox 44, Chrome 51, Opera 38, and Safari 9.1, a generic string not under the control of the webpage will be shown instead of the returned string. For example:
Firefox displays the string, "This page is asking you to confirm that you want to leave - data you have entered may not be saved." (see bug 588292).
Chrome displays the string, "Do you want to leave this site? Changes you made may not be saved." (see Chrome Platform Status).
I am using asp.net 2.0 with c#.
i want a pop up to be displayed when user tries to close the browser and if user click on "no" [i.e. he don't want browser to be closed] then it prevent browser to get closed.
Please help.
Thanks
the code they use is
window.onbeforeunload=function() {
if (somereasonorother) return "You did not save your stuff"
}
Pointy, this is entirely possible, and it's done by many web pages for perfectly reasonable reasons.
Try something like this:
function areYouSure() {
return "Are you sure you want to leave this page?";
}
window.onbeforeunload = areYouSure;
You can try to attach yourself to the onbeforeunload event:
<body onbeforeunload="ConfirmClose();">
But I have to mention that it won't work on all browsers. The only ones that prompted something after I closed a window were Chrome, Firefox and Internet Explorer; Opera ignored the code in the JavaScript method.
This is mostly because some browsers trigger the onbeforeunload event only when you're trying to leave the current page by visiting another one, and not when you close the current window / tab.