106 points · by Mojah · 11y ago · 105 comments
What we definitely shouldn't do (as the author suggests) is disable form submissions on subsequent clicks. What if the first response fails? You'll have to enter the entire form all over again, instead of being able to hit the back button. Madness!
The author's proposal makes things marginally easier for developers and shifts all of the pain to users. That's not really acceptable, at least not to me.
What's wrong though is the author's solution of disabling _all_ links and submit buttons on the page indefinitely. Here's an alternative solution that only disables whatever has been clicked on for half a second:
(function() {
function stopClickEvent (ev) {
ev.preventDefault();
ev.stopPropagation();
}
document.body.addEventListener('click', function (ev) {
if (ev.target.tagName === 'A' || ev.target.getAttribute('type').toLowerCase() === 'submit') {
setTimeout(function () {
// Needs to happen _after_ the request goes through, hence the timeout
ev.target.addEventListener('click', stopClickEvent);
}, 0);
setTimeout(function () {
ev.target.removeEventListener('click', stopClickEvent);
}, 500);
}
});
})();
Unlike the author's solution, this really works for links (they don't support the `disabled` attribute), it doesn't change the appearance of the button, it only disables one element, and it will work for elements that have been added to the document after the DOM was loaded. You can try it here: http://codepen.io/anon/pen/xGKdLXOf course, a common source of duplicate form submissions is when then submission request is taking long (>1000ms) and the user gives the button another click in a little while.
It's not only the double-click that causes problems. For example, user might click and if the server does not respond right away it might seem that click did not get accepted, so the user will try to click again 3-4 seconds later. The one-time token solves this problem as well.
Then you might have AJAX stuff that gives no feedback until the server does its job (which might take a while if it's under load at the time) and if you disable the button it prevents the user to retry. Sure, you can add indeterminate progress bars and animations, but users quickly learn to ignore those if they don't get any response from the server in expected time.
What really should be done is educating developers to implement this pattern. Any beginner book that talks about HTML and HTTP should include this. Unfortunately, it's so easy to enter web development today that many people have to learn from their own mistakes, and reinvent the wheel over and over again.
Maybe I'm too pessimistic, but I just don't see it happening.
In fact, the same technique should apply to session tokens in general. They should be signed by the server, which removes the need to do I/O to filter out unauthorized sessions and mitigate DDOS attacks.
So yes, this is the correct way to do it. But additionally, I don't see why it's so bad for the client to prevent quick submissions in succession... maybe disable the button until the response comes back, with a 1 second timeout, and alternate suggestions on repeated failures.
And also the CSRF token doesn't need signing, it comes from the session data stored on the server. The session id is what needs signing.
Once an account is created, throttling resources is straightforward. If you want, you can allow a person to have one X per Y (time, points, whatever).
Say you double click on some action with a one time token, the first request gets to the server and succeeds while the second request fails due to the token being used. But, the response to the first request is delayed and the second response (failure) gets to the client first. The client can either 'obey' this failure response or wait till all in flight requests return (or maybe till one comes through with success). The solutions to dealing with this look a lot like debouncing/throttling the requests in the first place.
Using a one time token is very useful for avoiding multiple executions of non idempotent operations but it's really a separate issue from dealing with multiple requests/responses on the client. i.e. the UX.
Request 1 takes the 'token'
Request 2 sees the token gone, returns 'silent success'
Request 2 response reaches client, client assumes success.
Request 1 fails somewhere internally
Request 1 returns failure to client, which has already acted on the success of request 2
User thinks the action was successful, when it wasn't.
Now, you can build yourself a lovely two phase commit system around the token and the operations performed by the action to deal with a UI issue, or you can just throttle the requests.
As an aside, the distinction between double click and single click used to be much clearer (in Windows 3.1/95 times!):
- If its on a white background, maybe in a well, then it is a selectable. Click on it to select it, right mouse button to do something with it, and double-click to do the default action with it (which is bold in the context menu).
- If it looks like a physical button (3D and raised), then you can perform an action by clicking on it.
Links are a bit odd, as they look selectable (and in fact they are, by clicking and dragging from outside in), but one click performs an action. But by now, they are so ubiquotious that everybody knows that one click activates them (Well, at least one click. Two clicks do no harm in most situations.)
What I hate about modern flat design is that it often removes these hints towards what kind of control something is (the "affordance" in hip UX speak). If I click/tap on something, does it get selected, opened, or does nothing happen because it is a label? No way to know without trying.
To have better response time (and be a good citizen and save bandwidth), if you try to load in quick succession two different pages the first request is aborted. If you're too late the content of the first request has already been downloaded and being processed, resulting in that page being loaded.
But, saying that idempotency is hard and thus we should build features to get around it.. that seems wrong to me. The web is inherently a distributed system and you're going to have concurrent requests and weird edge cases that arise in those situations. The right way to handle that isn't to bandaid it with disabling client side behavior. That just hides to problem. Your server is the place to handle it.[1]
And, it really isn't that hard either. It's just a couple extra validations on your input before you do a write. There are places where it is more difficult but still not overly complicated to implement.
[1] Dogmatism alert. Of course, there are exceptions to everything that's a 'best practice'. Here, I'm just talking about disabling double-click as a general solution for the web to a concurrency problem.
The author says "Server-side, this is a much harder problem to solve." and he is correct. But that doesn't mean that if the browsers did solve this problem that you wouldn't still need to solve it server side. For the same reason you still need to implement server side validation even though you have client side validation (never trust user input).
Say you had an order form only allowing one order per customer (some special offer) and on the server you have a check to ensure order.count==1 you might assume that because the browser prevents double clicks on the form you are now safe. Except you aren't. It's pretty trivial to still send that form submission multiple times simultaneously (curl, ab) and trigger a race condition where each order.count check returns 0.
Indeed it is possible to implement idempotent behavior of POST forms server-side. Even if a bit tedious to implement at first, it meshes very well with multi-user web apps, when several people may be changing the same underlying data simultaneously.
One possible approach is carry in POST both old (original) state and new (user input) state, and apply it as a diff to underlying storage.
Used this approach with 100% success on WWW based kiosks used by tradesmen, some of whom were habitual doubleclickers. Since the form was very simple -- one or two fields -- the old state was carried in action url. In case of double clicks, the seconds ended up changing nothing in backend storage, and returning correct data.
I see alot of younger people are like this about some things. (but not single-clicking obviously.)
How about raking your scrollwheel through fifteen pages to get somewhere? Analog scrolling, I call it. Because that's what it is, a skeuomorph of scrolling through a microfilm... I would've thought the advantage of having a computer was that you can go directly to page n, to line n, whatever.
In terms of efficiency, I would liken the scroll wheel to the arrow keys: it's alright for small distances, but not more.
I can understand that single vs double clicking can be an issue with non-technical users, but disabling double click won't really change that issue, because they usually don't understand that these are two different actions. Of course one can and should try to make things easier for them, but once it starts to affect the usability for others, it's not really worth it anymore. These people should learn to adjust their behavior.
Now that this is out of the way, I really wonder what he meant with:
> For techies like us, a double-click happens by accident.
What kind of techies is he talking about, because I'm using the PC many hours each day and I don't just accidentally double click stuff. Maybe it's the environment they're working with, but for me I'd say, I do a larger portion of single-clicks than double-clicks per day and if a signification percentage were accidental double-clicks I would have more issues that just a site that opens twice.
And last but not least I'd say a big percentage of my clicks on the web are middle clicks anyways, i.e. open link in a new tab. Something that wasn't even looked at, which again makes me wonder how the author is using the web.
What we can learn from this however is, that websites should add checks to prevent double submissions of forms. And provide proper feedback if e.g. an AJAX submission failed or if it's still sending data.
We're not "trained to double-click anything", unless some particular trainer is extremely misguided.
Double-clicking is used when there is some action available for an item in addition to the single-click action, where the double-click usually leads to both actions taking place: we single-click to select files and double-click to open them, single-click the title bar to activate the window and double-click to maximize, single-click the window menu to view the menu and double-click to close the window (which is one of the options in the menu).
Some examples of things we only single-click: buttons, scrollbars, tabs, menus, dropdowns, text (for selection).
Single-click is everywhere. Everything that can be double-clicked can also be single-clicked. Single-click is the default. If a single-click only leads to an item beings selected, that's a pretty good hint to try double-click if you also wanted it to be opened.
(Incidentally, what do those who double-click everything do when they want to select a file? Do they just open it, close it again (leaving it selected) and accept that as normal?)
I can't remember the last time I had to double-click anything, except for text selection.
Clicking an item in a list should select the item. Double clicking an item in a list should open it. This is the part that might be broken in the web browser because I see check boxes and all sorts of other UI gymnastics to enable the functionality of how a list works in file browsers, and email.
There are a few other UI things in the web browser that I think are slightly broken. These UI things are a legacy from the original web browser. For example check boxes and radio buttons separate the text from the check/radio box, but I think you should be able to click on the text to toggle the box -- yes, I know there are work-around using JavaScript, but basic UI should be consistent.
I disagree. By far the most actions are performed with a single-click, double-clicks are mostly for one very specific use case - having a container control and you want to select one of the children and perform the default action on it.
"because our brains are just hardwired to double-click everything." that might be true for people that formed muscular memory in the golden days of the mouse and heavy OS use (as oposed to heavy internet use).
An acceptable solution has to anticipate the muscular memory we are generating in legions of mobile users: tapping.
If we apply that author's central argument to today's mobile influence, then who instead of tapping will have her brain just wired to double tap?
In Android 5.0, swiping from the top brings up the notification menu and a two-finger swipe brings up the settings shortcuts. From the shortcuts screen, the back button brings you back to the notification menu. Another press of the back button brings you all the way back to where you were.
So to quickly go back after bringing up the shortcuts screen, you would naturally press the back button twice in quick succession. But that's a lot like a double-click, and if we want to treat those as single-clicks ... it has to ignore one press and just bring you back to the notifications screen instead. Which is exactly what happens.
So to actually go back twice, which is a very common and natural thing in this case, you have to go back ... then wait ... wait ... and then finally go back again.
> If the same form submit has been registered by the browser in less than 2 seconds, surely that must have been a mistake and would count as an accidental double-click?
Or maybe they're using POST requests to control some process which they get feedback from through another channel. They could be rotating pieces in a Tetris game – should I have to wait for 2 seconds between my two identical commands for rotating a piece 180 degrees to the right?
I'd flip the proposal around, and go for:
<form action="/something" onlyOnce>
...
</form>
The problem then is for the hung responses which still happen frequently enough, the typical hack to unfreeze a requeust is to mash the link/button a second time. Now, would the user have to hunt for the "Cancel" button (an increasingly diminishing target) before being able to click Submit again?Since you can't guarantee a client will have this behavior, you have to plan for it anyway on the server. I think that's why features like this tend not to be deployed. Features that might help most of the time tend to be beaten to death by the people who keep insisting that they don't completely and entirely solve a problem, so somehow that means it's better not to have them at all, i.e. false hope.
if your attribute is written as onlyOnce
That's not to say that it isn't a bad idea, but I don't think the inconsistent behavior in jQuery should be considered in arriving at that conclusion.
$(document).ready(function(){ $("form").submit(function(){ setTimeout(function() { $('input').attr('disabled', 'disabled'); $('a').attr('disabled', 'disabled'); }, 50); }) });
EDIT: Oh, never knew that this method was a Node-ism only.
[1] https://developer.mozilla.org/en-US/docs/Web/API/Window/setI...
var setNextTick = function(nextTickFunction){window.setTimeout(nextTickFunction), 0})
...sounds like a damn good idea.Hate the name 'setImmediate' though, immediate implies the current tick and people would wonder why you're using it.
This allows for the best balance between preventing double-submission errors, and a good user experience if a user has made an error.
I still de-dupe check on the server too (in case JS is disabled), and in a distributed environment the server submissoin de-dupe check isn't guaranteed (what if two submissions went to different servers?).
Perhaps if anything should be added to browsers it's simply a checksum of all of the values to submitted and an option to prevent submission if a prior checksum has been submitted. But even then... this is trivial to do in JS.
The above only applies to POST, for GET I don't care... it's cached, and perhaps the second request is the because the first one stalled (bad mobile network, etc).
If submission gets stuck and doesn't go through (because mobile networks, public wifi, and "cloud" servers have more failure modes than we'd like…) user is stuck with permanently-disabled buttons and can't retry submitting.
E.g. https://bugzilla.mozilla.org/show_bug.cgi?id=224026 https://bugzilla.mozilla.org/show_bug.cgi?id=873045
There's no excuse, but they don't fix it.
Browsers exist for my convenience, not yours.
When I was getting into nodejs a few years back I wrote DoS script to kill a site that was scraping content from one of my sites and posing it as their own. I made it just for shits n giggles in about 5 minutes and I was surprised when it actually worked, their website just went down.
DoS is and always will be easy.
Yes, I expect everyone who writes a web application to make it able to handle server requests reliably. There is no such thing as making a robust request -- a browser is just a browser. It doesn't know enough about your server to know what it doesn't like or can't handle. It also doesn't know enough about the user to know what their intent is.
You are blaming the pipeline for end-point issues.
plus... double click means double RSI no?
And now on the subject of double-clicking, it occurs to me that if the one-finger thing hadn't been the way, everything that was ever a double-click action could've just been a single click on the next button over. Which would be simpler.