Prevent an accidental Back Browse - javascript

I have a client that just got the Apple Magic Mouse. We built a recipe website and she get very upset when she is inputting all the information for the recipe, then goes for her new mouse and accidentally scrolls to the right and it will do a Back Browse and all her info is lost. So she wants to warning/pop up to prevent this from happening on that page.
Any suggestions or point me to some JS that does this?

This is a basic 'warn before leave' script. When the user presses a key in the textarea, the user will be notified if (s)he is about to leave the page:
<script type="text/javascript">
var changes = false;
window.onbeforeunload = function(){
if(changes){
return "You're about to leave this page.";
}
};
</script>
<textarea onkeypress="window.changes=true">recipe here</textarea>
Alternatively, you can store the contents of the textfield in a variable when the page loads and compare it afterwards. This will take away some confusion when the visitor just press the arrow keys in the textarea without actually modifying it.

So she wants to warning/pop up to prevent this from happening on that page.
You can hook into the onBeforeUnload event of your browser and then show a confirmation message.

Related

Adding additional function to exit page popup message

I want to add an additional function to a basic plain javascript exit page popup. Basically, I have my page set up so when a user tries to exit the page a message will appear saying "do you really want to leave" with the options "OK" and "Cancel". I want to set it up so when the user clicks OK it will redirect them to another website. I don't have a lot of experience coding so I'm not sure if this is possible. Here is the code that I'm using:
<h1 id="home">Warn before leaving the page</h1>
<script>
// Warning before leaving the page (back button, or outgoinglink)
window.onbeforeunload = function() {
return "Do you really want to leave?";
//if we return nothing here (just calling return;) then there will be no pop-up question at all
//return;
};
</script>
<a href="http://google.com/</a>
Any help will be appreciated, Thanks!
This is something you should avoid doing because it is bad user experience. Also this is a repeat of this post.

Detect if the user arrived to the current page via the browser back button

I have a site where if a user navigates to a certain page then he gets a dialog notification depending on some condition on the page. The user can navigate to other pages from this page and of course can press the back button on those pages to navigate back to this page.
I'd like to detect if the user arrives via the back button to this page, so the dialog notification is not shown again (because the user has already seen it).
Is there a way to detect this reliably?
MDN list of window events
Your best possibility may be window.onpageshow = function(){};
An event handler property for pageshow events on the window.
window.onpageshow = function(event) {
if (event.persisted) {
alert("From back / forward cache.");
}
};
Input trick is not longer working. Here's the solution I use:
if (window.performance && window.performance.navigation.type === window.performance.navigation.TYPE_BACK_FORWARD) {
alert('Got here using the browser "Back" or "Forward" button.');
}
The best (although not TREMENDOUSLY reliable) way is to use the Javascript history object. You can look at the history.previous page to see if it's the next in the series. Not a great solution, but maybe the only way to figure it out.
I like use a value in an input field for this:-
<input type="hidden" id="fromHistory" value="" />
<script type="text/javascript">
if (document.getElementById('fromHistory').value == '') {
document.getElementById('fromHistory').value = 'fromHistory');
alert('Arrived here normally');
} else {
console.log('Arrived here from history, e.g. back or forward button');
}
</script>
This works because the browser repopulates the value of the field with the one the javascript puts in there if it navigates back to it from history :-)

How to redirect to another page when confirm is clicked in the confirmation box using javascript?

I have the following code:
<html>
<head>
</head>
<body>
<form method="post" action="something.php" name="myForm">
<input type="submit" name="homepage" value="Please Work" id="homepage">
</form>
<script>
var btn = document.getElementById('homepage'),
clicked = false;
btn.addEventListener('click', function () {
clicked = true;
});
window.onbeforeunload = function () {
if(!clicked) {
return 'If you resubmit this page, progress will be lost.';
}
};
</script>
</body>
</html>
This code pops a confirmation box when the user leaves the page (Back or Refresh Browser Button) but not when a button inside the form is clicked.
QUESTION
How can I redirect to a different page when the user clicks the "Leave this Page" button of the confirmation box? I tried different methods but it does not work. I'm using Google Chrome.
Any help is very much appreciated. Thank you in advance. :)
EDIT
So I got some codes that actually works but it does the opposite. When I click the "Leave this Page" it stays and when I click "Stay on this Page" it redirects.
var onUnloadClick = 0;
function redirectTimer() {
setInterval(function(){window.location = "sample exam.php"},10);
}
var btn = document.getElementById('homepage'),
clicked = false;
btn.addEventListener('click', function () {
clicked = true;
});
window.onbeforeunload = onbeforeunload_Handler;
function onbeforeunload_Handler() {
if(!clicked) {
if(onUnloadClick == 0) {
redirectTimer();
return 'If you resubmit this page, progress will be lost.';
}
}
};
QUESTION
How will I modify this code and do the opposite function?
You can't mess with the browsers processes. If you click back, it will go back. If you click refresh, it will refresh the page. The reason they're in there is because they have their functions. You can try different approach in doing what you want but I don't think this one is possible.
I dont think that its possible. Check out answer here:
Intercept selection in window.onbeforeunload dialog
There is not defined way to intercept the onbeforeunload event. Further reference can be seen here:
Intercept selection in window.onbeforeunload dialog
When onbeforeunload event is kick started the user has already selected where he\she wants to go; it would not make sense if the browser allows javascript on a webpage to override the actions of the user.
Hence there should not be anyway for you take the user to some other location other than where the user wants to go.
Updated Answer to the Updated Questions:
Its not possible to do what you are trying to do. The reason you get redirected when you choose "stay on this page" and not otherwise is because your javascript function to redirect comes into effect only why you stay on the page. When you choose to leave the page the browser will no longer execute any of your code. Because the browser does not want you to override the choice fo the user.
My recommendation:
Rethink what you want. You want to redirect the user to a different page when the user is trying to go somewhere else. I really don't think that is the correct.
What is your ultimate goal? If you let me know that.. probably I can provide you with a better solution.

Browser back button handling

I am trying to handle browser back button event but i could not find any solution.
I want to ask user if he clicks on browser back button using "confirm box" if he chooses ok i have to allow back button action else i have to stop back button action.
Can any one help me in implementing this.
Warn/confirm User if Back button is Pressed is as below.
window.onbeforeunload = function() { return "Your work will be lost."; };
You can get more information using below mentioned links.
Disable Back Button in Browser using JavaScript
I hope this will help to you.
You can also add hash when page is loading:
location.hash = "noBack";
Then just handle location hash change to add another hash:
$(window).on('hashchange', function() {
location.hash = "noBack";
});
That makes hash always present and back button tries to remove hash at first. Hash is then added again by "hashchange" handler - so page would never actually can be changed to previous one.

Prevent user from accidentally navigating away

My problem is a bit more complex than using the following simple JavaScript code:
window.onbeforeunload = function (e) {
return 'Are You Sure?';
};
On an e-commerce web page I would like to remind the user that he has items in the shopping cart so that he can change his mind before
closing the browser tab/window
navigating to another domain
The JavaScript method above does not solve my problem because it is evoked even when the user navigates within the domain.
Short:
User tries to close window -> Show dialog
User changes www.mydomain.com/shoppingcart url to www.google.com in the browser's address bar -> Show dialog
User navigates to www.mydomain.com/checkout with the checkout button or presses the back button in the browser -> Do NOT show the dialog
It's not possible to tell if a user is pressing the back-button or closing the tab and you don't have access to their intended location.
It is possible to stop the dialog from showing if an internal link is clicked though:
(function(){
function isExternal( href ) {
return RegExp('https?:\\/\\/(?!' + window.location.hostname + ')').test(href);
}
var returnValue = 'Are you sure?';
document.documentElement.onclick = function(e){
var target = e ? e.target : window.event.srcElement;
if (target.href && !isExternal(target.href)) {
returnValue = undefined;
}
};
window.onbeforeunload = function(){
return returnValue;
};
})();
Sorry there's no technical solution to your "problem."
It's not an accident when a user decides to leave your site, i.e. by typing a new URL, so stopping them to say "Hey, you haven't checked out yet" is kind of pointless.
I would suggest letting the visitor leave your website freely and simply remembering their information (DB, Sessions vars, etc). In terms of eCommerce that is the polite way of keeping customers.
If someone wants to leave your website, they will. Double-checking beforehand will likely only irritate the customer and lessen your chance of their return.
Since the beforeUnload-event object does NOT contain the location the user is trying to go to, one "hack" to do this would be to add click listeners to all links on your site, and disable the unload-listener in that handler. It's not very pretty, and it will probably not work if the user navigates with the keyboard, but it's my best guess at the moment.
It sounds like you'd need to use an onbeforeunload and then modify all your internal links to disable it. Probably the thing to do for the latter would be a jQuery event; making the actual hrefs run through JS would be terrible, not least because it'd defeat search engine crawling.
I was looking into this too, reason being we have some really stupid end users who fill out a whole web form then don't press the save button.
I found this is u r interested, seems like a good solution:
https://web.archive.org/web/20211028110528/http://www.4guysfromrolla.com/demos/OnBeforeUnloadDemo1.htm

Categories

Resources