4 ms·
While I agree that you should include a one-time token with all sensitive forms, I don't think that disabling links/submit buttons on the first click is a bad i
by atomwaffel 11y ago
While I agree that you should include a one-time token with all sensitive forms, I don't think that disabling links/submit buttons on the first click is a bad idea in general. It's an easy fix that will immediately prevent most accidental redundant server requests, but as it's a client-side fix it's inherently unreliable.
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/xGKdLX http://codepen.io/anon/pen/xGKdLX
- 13 11y agoThis gets seriously annoying if you have an intermittent connection. I know the first click didn't succeed, so I have the choice of refreshing and losing all my typed content or manually using the web inspector to re-enable the button. It's shitty user experience.
- atomwaffel 11y agoSorry, you might want to re-read my comment. My solution will only disable the button or link that has been clicked on for half a second, which ought to be enough to both prevent accidental and allow intentional resubmissions.
- 13 11y agoAh! Yes I jumped to an assumption there. That's a much better solution.
- danneu 11y agoI like the 500ms timeout as a quick solution. Of 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.
- atomwaffel 11y agoI know, and you could set the timeout higher to prevent these (the button becomes a placebo button that's still clickable but doesn't do anything), but it gets hard to draw a line at which the request really might have failed and the button should be re-enabled. I feel like this is a different problem that needs to be addressed server-side, both with quicker response times and single-use tokens.