On using "confirm('message')" in JavaScript, making the browser navigation buttons disabled - javascript

I have a situation where in, when the user clicks the "back" button, I have to prompt for a "confirm" on a page using JavaScript. The result would decide whether to stay on the page or not.
I have used, the following:
window.onbeforeunload = function () {
var answer = return confirm("Please note by clicking the back button will reset your selection")
if (!answer) {
event.preventDefault();
}
else{
// do something
}
};
Now, even if this prompts a popup on the page, the back button can still be clicked taking the user to the previous page.
On the other hand, by using the following.
window.onbeforeunload = () => {return '';}
I get the message "Changes you made may not be saved.", with the prevention of "back", "forward", "refresh" and all such buttons on the page.
I want this same thing (the prevention of these buttons), to happen on "confirm('message')".

function Confirm_something() {
history.pushState(null, null, location.href);
window.onpopstate = function () {
history.go(1);
};
return confirm("Text you want?");
}
if(Confirm_something){
console.log('user say yes'); //then call your save edit or delete functions.
}
else{
console.log('user say no');
}

Related

How to show alert on leaving page before saved data? using only javascript. I dont want windows alert msg. i need normal Alert window

this below code is working correctly but i want alert of javascript one not windows alert.
unsaved = false;
$(":input").change(function () {
unsaved = true;
});
$(document).on("submit", "form", function (event) {
unsaved = false;
$(window).off('unload');
});
function unloadPage() {
if (unsaved) {
return "You have unsaved changes on this page. Do you want to leave page?";
}
}
window.onbeforeunload = unloadPage;

Javascript confirm Stop page refresh after cancel

I have made a JavaScript function which is attached to the cancel button on of a form. The issue I am finding is that when the cancel button is pressed the page/form reloads losing the data in the text fields.
function cancelConfirm(){
var confirmCancel = confirm("Are you sure you wish to cancel?");
if(confirmCancel==true)
{
alert("byebye");
}
else
{
return false;
}
};
I was just wondering how can you prevent the page from reloading after the cancel button on the confirm has been clicked? Thanks for any help you can give
you can just use a simple way
Delete
function cancelConfirm() {
var confirmCancel = confirm("Are you sure you wish to cancel?");
if (confirmCancel == true) {
alert("byebye");
return false;// to stop postback on ok cick of confirmation popup
}
else {
return false;
}
}
What you can do is to add an onClick event and pass the event object down to it.
{onClick(e) => {
e.preventDefault();
//do something here
}}
A simple e.preventDefault() is what you need.

Redirect to another url when back button is clicked using javascript

I have a payment form in which user can enter all his card details,and when he clicks,he is taken to the banks 3D secure page. But,the problem is, the user can simply click on the back button of the browser and can go back to payment page, if he initiates a "pay now" again,there is a chance of multiple transaction and duplication of ref ids.
So my question is: is there some way I can redirect the user to a custom page when he clicks on back button which says "Session expired, so transaction has been cancelled." so that we avoid duplication of ref ids?
Use the below jquery for redirect your own url when clicking browser back button
andipedia.com
jQuery(document).ready(function($) {
if (window.history && window.history.pushState) {
$(window).on('popstate', function() {
var hashLocation = location.hash;
var hashSplit = hashLocation.split("#!/");
var hashName = hashSplit[1];
if (hashName !== '') {
var hash = window.location.hash;
if (hash === '') {
alert('Back button was pressed.');
window.location='www.example.com';
return false;
}
}
});
window.history.pushState('forward', null, './#forward');
}
});
If user clicked back button this will redirect you to your specified
page (100% Working)
window.history.pushState({page: 1}, "", "");
window.onpopstate = function(event) {
if(event){
window.location.href = 'https://www.google.com/';
// Code to handle back button or prevent from navigation
}
}
You have to use history api, and for better compatibility use history.js plugin.
Handling pressing back button :
$(window).bind('onpopstate', function(e){
//your dark doings here
});
You can use Brooke's modified script. That's a long script (should be used as external file). You can download it here!
Then use the script like this:
bajb_backdetect.OnBack = function(){
document.location.href = 'http://google.com';
}

Notify user on browser close only

I am trying to implement notifying when the user closes or reloades the page.Crrently i am using the following code
function unloadPage(){
return "Your changes will not be saved.";
}
window.onbeforeclose = unloadPage;
This works fine.But the problem is this happens whenever a navigation takes place.That is either a page refresh or a form submission or a hyperlink click or whatever navigation takes place..I just want to work this code only for browser refreshing and closing.I knew about setting a flag and checking it.
But i have to integrate this in a big application.So it will be difficult to add the code in every page.So is there an easy way.
Is there a way to catch the refresh or browser cosing so that can use it.
Note that in your code, you're using onbeforeclose, but the event name is beforeunload, so property is onbeforeunload, not onbeforeclose.
I just want to work this code only for browser refreshing and closing. Is there a way to catch the refresh or browser cosing so that can use it.
No. Instead, you'll have to capture each link and form submission and either set a flag telling your onbeforeunload handler not to return a string, or removing your onbeforeunload handler (probably the flag is cleaner).
For example:
var warnBeforeClose = true;
function unloadPage(){
if (warnBeforeClose) {
return "Your changes will not be saved.";
}
}
window.onbeforeunload = unloadPage;
// ...when the elements exist:
$("a").click(dontWarn);
$("form").submit(dontWarn);
function dontWarn() {
// Don't warn
warnBeforeClose = false;
// ...but if we're still on the page a second later, set the flag again
setTimeout(function() {
warnBeforeClose = true;
}, 1000);
}
Or without setTimeout (but still with a timeout):
var warningSuppressionTime = 0;
function unloadPage(){
if (+new Date() - warningSuppressionTime > 1000) { // More than a second
return "Your changes will not be saved.";
}
}
window.onbeforeunload = unloadPage;
// ...when the elements exist:
$("a").click(dontWarn);
$("form").submit(dontWarn);
function dontWarn() {
// Don't warn for the next second
warningSuppressionTime = +new Date();
}
Update in 2017: Also note that as of at least a couple of years ago, browsers don't show the message you return; they just use the fact you returned something other than null as a flag to show their own, built-in message instead.
One of the simple solutions to your problem is to have a flag and then call your function only if the flag is valid. In this case , you can bind the anchor tags, F5 key and form submit button click to events that set the flag as false. So your alert bar will be visible only if the above cases don't happen :)
Here's the script:
var validNavigation = false;
function endSession() {
// Browser or broswer tab is closed
alert("bye");
}
function wireUpEvents() {
window.onbeforeunload = function() {
if (!validNavigation) {
endSession();
}
}
// Attach the event keypress to exclude the F5 refresh
$(document).bind('keypress', function(e) {
if (e.keyCode == 116){
validNavigation = true;
}
});
// Attach the event click for all links in the page
$("a").bind("click", function() {
validNavigation = true;
});
// Attach the event submit for all forms in the page
$("form").bind("submit", function() {
validNavigation = true;
});
// Attach the event click for all inputs in the page
$("input[type=submit]").bind("click", function() {
validNavigation = true;
});
}
// Wire up the events as soon as the DOM tree is ready
$(document).ready(function() {
wireUpEvents();
});
Check this link
It gives you information on how to handle onbeforeunload event.
The idea is to have a global flag on the page. When any change is done to the fields, this flag is set to true. When clicked on save button, then this flag needs to be set to false.
In the onbeforeunload event, check whether the flag is true, then show the message accordingly.
var needToConfirm = true;
window.onbeforeunload = confirmExit;
function confirmExit()
{
if (needToConfirm)
{
// check on the elements whether any change has been done on the fields.
// If any change has been done, then set message here.
}
}
function saveClicked()
{
needToConfirm = false;
}
DEMO
(Run or refresh the fiddle to see the alert onbeforeunload() event message and click on the link "kk" ,it wont show onbeforeunload() event message. Try it in your webpage)
I have a solution for you, you don have to add onclick event to each tags and all.
Just add this to any where on your pages .
<input type="hidden" value="true" id="chk"/>
and add this code to your document head tag
<script>
window.onbeforeunload = confirmExit;
function confirmExit()
{
if(document.getElementById("chk").value=="true")
{
return "Your changes will not be saved.";
}
}
document.onclick = myClickHandler;
function myClickHandler() {
document.getElementById("chk").value="false";
}
<script>
Hope this helps
Thank you

Activating OnBeforeUnload ONLY when field values have changed

What I'm trying to achieve is to Warn the user of unsaved changes if he/she tries to close a page or navigate away from it without saving first.
I've managed to get the OnBeforeUnload() dialog to pop-up... but I don't want it to be displayed at all if the user hasn't modified any field values. For this, I'm using this hidden input field called is_modified that starts with a default value of false and flips to true when any field is edited.
I tried to bind the change event to this is_modified field to try and detect for value change... and only then activate OnBeforeUnload.
$( '#is_modified' ).change( function() {
if( $( '#is_modified' ).val() == 'true' )
window.onbeforeunload = function() { return "You have unsaved changes."; }
});
But from what I figure is that the change() event works only after these 3 steps - a field receives focus, a value is changed and the field looses focus. In case of the hidden input field, I'm not sure how this receiving and loosing focus part works! Hence, the onbeforeunload function is never being activated.
Can anyone suggest a way to maintain a trigger over is_modified?
Thanks.
I had a similar requirement so came up with following jQuery script:
$(document).ready(function() {
needToConfirm = false;
window.onbeforeunload = askConfirm;
});
function askConfirm() {
if (needToConfirm) {
// Put your custom message here
return "Your unsaved data will be lost.";
}
}
$("select,input,textarea").change(function() {
needToConfirm = true;
});
The above code checks the needToConfirm variable, if its true then it will display warning message.
Whenever input, select or textarea elements value is changed, needToConfirm variable is set to true.
PS: Firefox > 4 don't allow custom message for onbeforeunload.
Reference: https://bugzilla.mozilla.org/show_bug.cgi?id=588292
UPDATE: If you are a performance freak, you will love #KyleMit's suggestion.
He wrote a jQuery extension only() which will be executed only once for any element.
$.fn.only = function (events, callback) {
//The handler is executed at most once for all elements for all event types.
var $this = $(this).on(events, myCallback);
function myCallback(e) {
$this.off(events, myCallback);
callback.call(this, e);
}
return this
};
$(":input").only('change', function() {
needToConfirm = true;
});
The following works well in jQuery:
var needToConfirm = false;
$("input,textarea").on("input", function() {
needToConfirm = true;
});
$("select").change(function() {
needToConfirm = true;
});
window.onbeforeunload = function(){
if(needToConfirm) {
return "If you exit this page, your unsaved changes will be lost.";
}
}
And if the user is submitting a form to save the changes, you might want to add this (change #mainForm to the ID of the form they're submitting):
$("#mainForm").submit(function() {
needToConfirm = false;
});
We just use Window.onbeforeunload as our "changed" flag. Here's what we're doing, (using lowpro):
Event.addBehavior({
"input[type=radio]:change,input[type=text]:change,input[type=checkbox]:change,select:change": function(ev) {
window.onbeforeunload = confirmLeave;
}
".button.submit-button:click": function(ev) {
window.onbeforeunload = null;
},
});
function confirmLeave(){
return "Changes to this form have not been saved. If you leave, your changes will be lost."
}
$(window).bind('beforeunload',function() {
return "'Are you sure you want to leave the page. All data will be lost!";
});
$('#a_exit').live('click',function() {
$(window).unbind('beforeunload');
});
Above works For me.
Try your logic in a different manner. Meaning, put the logic for checking the value of the input field in your onbeforeunload method.
window.onbeforeunload = function () {
if ($("#is_modified").val() == 'true') {
return "You have unsaved changes.";
} else {
return true; // I think true is the proper value here
}
};
in IE9 you can use simple return statement (re) which will not display any dialogue box. happy coding..
why not have the onbeforeunload call a function that checks if the values have changed, and if so return the "unsaved changes" confirm?

Categories

Resources