Prevent double submission with prevent window event issue - javascript

I'm using the following function to prevent double submissions:
$("#form").submit(function () {
var form = $(this);
form.find("input[type=submit]").attr("disabled", "disabled")
form.find("input[type=submit]").attr("value", "Processing");
});
It works fine, but then I have the following code which triggers an alert to avoid accidentally leaving the page:
function goodbye(e) {
if(!e) e = window.event;
//e.cancelBubble is supported by IE - this will kill the bubbling process.
e.cancelBubble = true;
e.returnValue = '¿DO YOU REALLY WANT TO LEAVE THIS PAGE?'; //This is displayed on the dialog
//e.stopPropagation works in Firefox.
if (e.stopPropagation) {
e.stopPropagation();
e.preventDefault();
}
}
window.onbeforeunload=goodbye;
The problem is if the user clicks submit and the realizes he didnt want to leave the page and clicks on stay on this page instead, the submit button is still disabled.
How could I re-enable it upon clicking stay on this page?
Thanks!

The button problem
You want to disable and enable the submit button so you know you going to touch the same kind of function and object twice, it is better to make advantage out of this in a function
function disableSubmit(form, enabled){
var submit = form.find("input[type=submit]"),
dataVar = enabled !== true ? "processing-message" : "send-message",
message = submit.data(dataVar);
submit.prop('disabled', (enabled !== true) );
submit.val(message);
}
I could make it even more generic for using it on each form. But the message in the button will display whatever you put in the data-attribute.
Cancel Submit
There is a problem with cancellation of an onbeforeunload event; there is no callback for it. The solution I came with is using a timeout. Since you don't know if the person canceled or not, I think 2 seconds is enough for the page to submit.
You have to have 2 seconds patient to get the submit button enabled again. But you can adjust it all you want of course
if (e.stopPropagation) {
setTimeout(function () {
disableSubmit(formObject, true);
}, 2000);
e.stopPropagation();
e.preventDefault();
}
The JSFiddle example

Related

Prevent page leaving and capture Leave button Jquery

I wish to prevent a user from leaving a page before clicking on submit button.And when he confirm leave i want to execute something (delayed leave).
i use this function
window.addEventListener('beforeunload', function(e) {
var myPageIsDirty = "d";
if (myPageIsDirty) {
e.preventDefault();
e.returnValue = '';
}
});
This surely warns the user. But my requirement to handle the leave button click event and do something
leave button confirmation can be done by:
Submit

Resuming default behaviour after preventDefault()

I've written a small jQuery plugin which is designed to ask the question, "Are you sure?" when clicking on a link or submitting a form.
It's used like this:
Link
Or like this:
<form action="link.php" method="post">
<button class="confirm">Submit</button>
</form>
What I am doing is using preventDefault() to prevent the default behavior when the anchor or button is clicked. I then display a confirm dialogue where the user has to click either OK or Cancel.
If the user clicks Cancel then nothing happens (as expected).
However, if the user clicks OK I am firing the click event again, and using a flag that was set first time around to not prevent the default behaviour second time around (I'm instead returning true). Except that it's not working. Clicking either OK or Cancel in the confirm dialogue doesn't do anything.
The plugin is below:
(function($) {
$.fn.fw_confirm = function(options) {
// Flag to check for the first click event
var paused = false;
return this.on("click", function(e) {
// The anchor or the button that was clicked
var button = $(this);
// If this is the second click event, the user must have confirmed so return true
if (paused == true) {
// Reset the flag
paused = false;
// This isn't working, or at least it's not submitting the form or proceeding to the URL of the hyperlink when I would expect it to
return true;
}
// First time around prevent the default behavior
e.preventDefault();
e.stopImmediatePropagation();
// Set the flag to true, ready for the second click event
paused = true;
if (confirm("Are you sure?")) {
// The user is certain, so trigger the click event again
return button.trigger("click");
} else {
// The user cancelled, reset the flag
paused = false;
return;
}
});
}
})(jQuery);

save user email before leaving page

On the cart page of my website, I have to intercept the user leaving the page and ask them if they want to save their cart via email.
I guess I have to use the event "beforeunload" to intercept the user leaving the page, but then I have two problems:
How to exclude from the "beforeunload" trigger the click on the link to proceed with the payment?
How to prompt a small form where I can ask for his email (to be used somehow later) and then proceed with the unload of the page?
For excluding on the link to proceed with the payment, you can do this :-
window.onbeforeunload = function() {
return "You're leaving the site.";
};
$(document).ready(function() {
$('a[rel!=ext]').click(function() { window.onbeforeunload = null; });
$('form').submit(function() { window.onbeforeunload = null; });
});
The only thing u can do is making a default browser messagebox appears...
window.onbeforeunload = foo;
function foo(e) {
if (!e) e = window.event;
//e.cancelBubble is supported by IE - this will kill the bubbling process.
e.cancelBubble = true;
e.returnValue = 'You sure you want to leave?'; //This is displayed on the dialog
//e.stopPropagation works in Firefox.
if (e.stopPropagation) {
e.stopPropagation();
e.preventDefault();
}
}

Detect browser/tab closing

I know how to display an alert to the user if they attempt to navigate away from the current page asking them if they are sure they wish to do so but I was wondering if there is a way to display this alert ONLY when the window / tab is being closed?
I'd like to only have the confirmation display when the window or tab is being closed, not when the user clicks a link.
Not possible.
the only thing close is the onbeforeunload event, but there isn't a difference (to javascript) between a closed window/tab or a navigation to another page.
Follow-up:
I suppose you could attach a click handler to every anchor on the page and use a "dirty" flag, but that's really hack-ish. something like (forgive me, but using jquery for simplicity):
(function(){
var closingWindow = true;
$('a').on('click', function(){
if (this.href == /* on-domain link */){
closingWindow = false;
}
});
$(window).on('beforeunload',function(){
if (closingWindow){
// your alert
}
});
})();
but that's about as close as you're going to get. note: this isn't going to help if another javascript function uses window.location, etc.
You cannot differentiate between the two.
window.onbeforeunload is triggered immediately before the browser unloads its resources. You do not know the reason for the unload, only that it's about to occur:
From the MDN:
An event that fires when a window is about to unload its resources.
The document is still visible and the event is still cancelable.
How about doing something like this?
Have a global variable set to false (i.e. var hasCLickedLink = false;)
On all your links (<a>), attach an event handler that sets the variable to true
On onbeforeunload, check the value of the variable to see if a link has been clicked or not. If it is still false, then they haven't clicked a link so give them the alert.
You need to explicitly specify events for which you don't want to show confirmation dialogue box.
var validNavigation = 0;
function bindDOMEvents() {
// Attach the event keypress to exclude the F5 refresh
$(document).keydown(function(e)
{
var key = e.which || e.keyCode;
if (key == 116)
{
validNavigation = 1;
};
});
// Attach the event click for all links in the page
$("a").bind("click", function()
{
validNavigation = 1;
});
// Attach the event submit for all forms in the page
$("form").bind("submit", function()
{
validNavigation = 1;
});
// Attach the event click for all inputs in the page
$("input[type=submit]").bind("click", function()
{
validNavigation = 1;
});
};
$(document).ready(function()
{
bindDOMEvents();
window.onbeforeunload = function () {
console.log(validNavigation);
if (validNavigation == '1')
{
console.log("No Alert.. Continue");
}
else
{
return false;
}
};
});
This solution worked for me in Firefox with Violentmonkey.
It is used like most of all window.onbeforeunload and check if left mouse button was pressed. So if pressed, this mean, click at free space or link opens - not closing tab.
function DetectBrowserExit()
{
if (butpres == 0) {
//your action before closing tab, alert not showing
}
}
window.onbeforeunload = function(){ DetectBrowserExit(); }
// the key is pressed, then when window.onbeforeunload - link is opening, so, tab not closing
document.addEventListener('mousedown',function(e){
if (e.which == 1) { //1-lbutton 2-mb 3-rb
//e.preventDefault();
butpres = 1
setTimeout(function() {
butpres = 0 //if after 3 seconds the script still works then the link has not been clicked, clear the click and continue to catch new clicks
//alert(butpres);
}, 3000); //Two seconds will elapse and Code will execute.
//alert(butpres);
//command_lock();
}
},false);

Stop User Leaving Before Postback (Javascript/ASP.NET)

I have several functions running on a postback that can take a little time to complete.
When postback is initiated I show a loading image with this code:
function showLoader()
{
document.getElementById("<%=loadingImage.ClientID%>").style.visibility="visible";
}
I want to be able to add code to this function so if user tries to leave at this point they are informed the operation is not complete.
I found this code:
function goodbye(e) {
if(!e) e = window.event;
//e.cancelBubble is supported by IE - this will kill the bubbling process.
e.cancelBubble = true;
e.returnValue = 'You sure you want to leave?'; //This is displayed on the dialog
//e.stopPropagation works in Firefox.
if (e.stopPropagation) {
e.stopPropagation();
e.preventDefault();
}
}
window.onbeforeunload=goodbye;
This works but I only want the code to be active when the loading image is active.
I tried the following but it shows the alert message when the page eventually posts back:
function goodbye(e) {
if(!e) e = window.event;
//e.cancelBubble is supported by IE - this will kill the bubbling process.
e.cancelBubble = true;
e.returnValue = 'You sure you want to leave?'; //This is displayed on the dialog
//e.stopPropagation works in Firefox.
if (e.stopPropagation) {
e.stopPropagation();
e.preventDefault();
}
}
function showLoader()
{
document.getElementById("<%=loadingImage.ClientID%>").style.visibility="visible";
window.onbeforeunload=goodbye;
}
Any ideas how I can tweak this to just show when user leaves page and not when postback completes?
You need to set window.onbeforeunload to null when a form get submitted. So, basically:
<form onsubmit="window.onbeforeunload=null">
To apply this on all forms dynamically, I'd suggest to write a window.onload function for this which does this without the need to edit every single form on all your pages.

Categories

Resources