JavaScript - detect browser stop button click - javascript

I have a form that disables submit button, when it is clicked.
But what if the user clicks browser "Stop" button.
Then he will not be able to resubmit the form.
Is there any way to handle such cases, possibly detecting Stop button press?

What is the reason for disabling the submit button?
You are trying to avoid double-clicks? -> you can disable the submit button for only a brief period of time, re-enabling it again on a timeout.
You are trying to avoid impatient reload-clicking? -> the same, but with a longer inactivity period.
You are trying to stop a form being submitted twice causing duplicate actions to occur? -> you can't fight this just with button disabling, as going back/forward will cause the page to be reloaded, likely keeping old form content but not the disabledness state, unless short-circuited by bfcache. In this case you must create a one-use token or new item ID that cannot be used more than once, and put it in a hidden field in the form. The server can check for it and disallow duplicates.
possibly detecting Stop button press?
Avoid onstop, it's not really reliable. Apart from browser support issues, it can't catch all possible combinations of navigation and stop/reload/etc. You'll never know how far the server script got, whether it performed an action.

Your best bet would be to detect the submit button on the server, so it can only be submitted once. This way, no matter what happens (firebug etc), the form is only submitted once. There is an OnStop() event, but it is IE only, and I would not recommend using it.

document.onstop
You can find documentation for it here:
http://www.codeguru.com/forum/archive/index.php/t-437967.html
https://developer.mozilla.org/en/DOM_Client_Object_Cross-Reference/document

Related

Can you stop a page from reloading on form submit without preventDefault with svelte kit?

I want to display a toast for a few seconds whenever a user does something, eg. when they log in to the app. I am using a form on /login/+page.svelte to login, with the database interaction in /login/page.server.js. And I am using a writable store to store toasts.
On form submit, the page refreshes, so my store is cleared and the toast is lost. It seems the event flow is:
submit form to /login/page.server.js
page.server.js does some stuff
page.server.js sends back the full page and the browser reloads to the new full page.
I understand you can use preventdefault to prevent all those steps, but I only want to prevent the reloading. Preventing everything does not seem optimal (there are probably some other stuff I don't even know I'm preventing).
Is there a nicer way of interacting between a page.svelte and a page.server.js without reload (and thus clearing, probably all, stores) than preventdefault + using a manual fetch?
REPL I was playing around with that demonstrates the toast staying full 3 seconds generally, but immediately disappearing on normal form submit.
https://svelte.dev/repl/8b61434332ca471b83cbf039bf1f3fc9?version=3.22.0
The intended workflow for forms is to use form actions and enhance, which automatically processes the form asynchronously (which falls back to the hard reload if JS is disabled).

disable manual page refresh and allow programmatically only

I'm want to disable the manual refresh but still allow it throw code only.
the page is responsive so the mobile refresh(drag down) is also need to be disabled.
I've tried already to preventDefault with:
window.onbeforeunload
window.onunload
and jquery:
$(window).unload
You cannot disable a refresh - you would enforce the user to stay on your page.
A common way (like jsfiddle and others) that is used when there's unsaved state, is to trigger a popup that asks the user if the page should really be left.
This is useful if some input hasn't been saved - having just some content that is refreshed over time it may be more annoying for the users.
A possible solution is found here

Button not enabling on refresh

User clicks and button gets disabled.
User reloads page.
Button is still disabled.
I want it to be enabled.
I have tried anything from onkeypress f5 to onbeforeunload and nothing works.
This is an issue I had the misfortune of encountering before, since most browsers rely more and more on local cache to improve page loading. While in chrome usually another page refresh fix it, Firefox is more stubborn.
I solved it by running a function using body onload event. This function detects those incorrectly disabled elements and re-enables them.
To avoid errors there must be a check to indicate weather this page has the elements to check in the first place.

Jquery: how to handle "stop/cancel" event when user stops form submit?

I found this question but it wasn't answered: Is there a jQuery event that I can monitor if form submission is cancelled?
So if the user submits a form, while it's loading the user pressed "esc", or clicked "stop" button of the browser, I want to invoke a function, is it possible?
Note: I know we can bind "esc" button, but what about if the user stopped the submission by the browser's "stop/cancel" button?
Is there a JavaScript or jquery possible solution?
EDIT:
I know we can handle this issue with XHR (json/ajax) post, but I'm looking for a normal form submission.
Simply what I'm trying to achieve is this: when the user presses the "submit" button, I want to disable the submit button. If the user cancelled/stopped the submission while it's loading, the submit button will still be disabled (should be re-enabled if submission was cancelled/stopped).
Edit/Rephrase - 16th Dec 2013:
My problem is similar to this: Is there a jQuery event that I can monitor if form submission is cancelled?
For example, I have this form:
<form method="post" enctype="multipart/form-data">
<input type="file" name="imginput" value=""/>
<input type="text" name="textinput" value=""/>
<input type="button" id="submitbtn" value="Submit"/>
</form>
Here's the problem scenario:
A newbie user fills up the form, then double-clicks the submit button. The same form values are inserted into the server twice!
Trying to Achieve:
I want to disable the submit button on click with $('#submitbtn').bind('click', function() { $(this).attr('disabled','disabled'); $(this).prop('disabled', true); });, which solves the problem but creates another problem: if the user clicked "esc" or stopped the browser while the form is still submitting, the submit button would still be disabled and the user cannot re-submit the form any more, I want to re-enable the submit button as soon as the "submission process" is cancelled. Is there a way to achieve this? Something like: $(window).onStop(function() { ... }); ? or a way to indicate that the submission process has been interrupted (or still running)?
Notes:
Looking for client-side (javascript or jquery) solution. I know it can be solved easily with server-side checking for identical entries, but I'm not interested in server-side solution.
Problem can be solved with XHR (ajax/json) bindings (like onSuccess, onFailure, etc).. but in this case, I'm using a normal post, not XHR, so please exclude XHR from your answer.
Solution has to solve the problem at least for the 5 major browsers (IE, FF, Chrome, Safari, Opera).
Someone may suggest that we bind "keypress" for the "esc" button, so when the user press "esc" we re-enable the submit button. That's good, but that's half-solution. What if the user stopped the "submission process" by the stop button of the browser, is there a way to indicate that this stop button has been clicked?
Finally, this question actually breaks down the complex problem and can thus be addressed in parts, as it should be. First, let's get the elephant out of the room:
there is no cross browser solution that detects when the user hits a stop/(ref) button
I actually looked this up for a while and couldn't find how to do it but maybe someone can provide an answer to that and enlighten us both. Now, let's get the 2nd elephant out of the room.
No Ajax requests allowed (for some reason). Once the user has hit the submit button and the actual submit event triggers away, we are STUCK
It's a fact that we being able to do things while some request is being processed is what is called Asynchronous (like the first "A" in "Ajax"). Let's see the 3rd elephant
I have dumb/inexperienced/clickety-clackety/abusers users that can create inconsistencies on the server (ie: unwanted duplicates) by accident. We should provide a mechanism to impede such event.
Disabling buttons is, of course, the easiest solution in this dilemma. We capture the submit, put in a line to disable any further submit events from that form. Done. May the next elephant come in?
The process has begun, the user sees the progress indicator spinning and realizes he just fucked up. He wants to stop it, HELL! he needs to stop it.
Problem, the user doesn't know (and he sure as hell shouldn't need to know) if the server already has complete headers and is processing the request. The server can listen to see if the client aborted but...
The user hit the stop button! did the server process the request? did the server dump it? did my data hit the database? oh, now I have a disabled form that I can't use anymore, and I don't know if what I did had consequences. How about a refresh?
Now your issue has a bunch of big holes in it that are worsened by the fact that YOU do NOT want your requests to be ASYNCHRONOUS, AND there is NO WAY to listen for browser.onStopreliably.
My Answer
Think things differently.
You are afraid of inconsistencies. Solution: disable submit events after the first
Your users are dumb/inexperienced. Solution: big red label Warning: do not press the stop button during the process, or navigate away from the page until the request has completed.
Your users are worried. Solution: add a caveat You may edit your post/info in another page once the request has completed. (some instructions to find the edit page)
Your server (or slow connection) is taking too long to finish and the user may be impatient. Solution: set a timeout event before triggering the submission that will... but wait! the request is Synchronous which means nothing else can be done until it's finished. Dear User: this process may take a while. If after X mins you have not been redirected to this/page.html please... (do something/more instructions)
Take all this advice and start using Ajax if you want higher levels of interactivity, educate your users on the hazards of trying to abort requests and give them options to edit afterwards.
Follow examples of other services. Many companies warn very strongly during payment procedures to be patient until the process has finished and add some instructions just in case something goes wrong and the user is worried.
Consider adding limitations to the interactivity, some processes are just not meant to be interactive (payments, unique entries...)
If you are worried that a user will leave himself stranded on a disabled form then add some info to him. If you tried to stop the procedure please follow this link to see if it was processed, if it wasn't you will be redirected to this form again (you may want to save the users form data so he doesn't have to start over)
Internet Explorer has a document.onstop event that is fired, but other browsers don't seem to support that. Note that it's fired when the user clicks Stop or hits Esc, OR if the user navigates to another page during page load, which has the same effect.
I don't believe there is a reliable way to trigger an event on clicking Stop in other browsers. Perhaps it would be possible to do something like: keeping the connection to the server open (as in the Comet approach), streaming some sort of keep-alive down the connection, and detecting if the stream ends (as I assume it would if the Stop button were clicked).
From: Any javascript event occuring when user clicks Stop load button?
I based my answer on the comment hanzo2001 added in his question:
"The whole idea is prevent the user from clicking the "submit" button
more than once, so the user don't submit the same form twice or more."
Then you could possibly have a wasNeverSubmitted flag, and set it to true after the first form submit.
Finally you'd check this flag for every form submit, if true, then you cancel the form submission, see how to do this on this question Disable submit functionality for all forms on a HTML page
The code would look something like below:
HTML:
<form class="js-form-submit-once">
/* .. form elements here*/
</form>
Javascript (requires jQuery):
var wasNeverSubmitted = true;
$('js-form-submit-once').on('click', function(){
if( wasNeverSubmitted ){
wasNeverSubmitted = false;
/* ... do nothing, let it submit */
}
else {
return false; /* cancels form submission */
}
});

Alternatives to disabling / disable back button in firefox and IE

Our application forbids going back for several reasons.
Basically because that's just how our application works (JSF with facelets as GUI)
You always have to enter on the welcome site, once you chose an application-flow you can only leave / abort when you tell the application (e.g. press a button). If you just browse away e.g. enter "example.com" in the address bar the state of your flow gets saved and once you relogin, you can resume the work. Going back is only possible when it was specifically designed like this with a 'back' submit - button.
Of course users keep pressing the 'back' button (i would do so as well) and they keep getting 'error: session out of synch'. This is a learning process and a couple years ago we just disabled the back-button to make things clear. Sadly this is no longer supported.
So instead of teaching the user the hard way and forcing him to relogin, are there some good alternatives I'm missing?
i found this link which should offer 3 methods to disable the back button - but in reality it just further confirms the fact that it is impossible to do it in a semi-nice way.
when the user tries to go to a previous page you can redirect him to the page he should be at in other words catch the "out of sync" and redirect him
You might find a workable solution here How do I insert an entry into browsing history via JavaScript
by inserting an extra step into the browser's history (perhaps a link to the current page with query string parameters that result in a nice big red box message to the user), or you could try attaching an event handler to the OnBeforeUnload event so the user gets a confirmation dialog when trying to leave the page (you'd want to remove the handler when the submit button was clicked).

Categories