Alt + left arrow is standard in most newer browsers for the back button.
As this works in IE as well there is still a way for users to navigate back with their keyboard.
Technically this could be considered a fail as you are interfering with expected behaviour, but I personally think that the inconvenience of having a whole form disappear trumps that so if you decided to disable the backspace key if the currently selected input is empty that would be OK.
Make sure that this only stops normal backspace behaviour if an <input>
is currently selected though (or <textarea>
) using something like document.activeElement
.
This way users can still use backspace to go back if they do not have an input selected.
A "catch all" solution removing the need to disable backspace
One way that you can solve this without disabling the backspace button is with window.onbeforeunload
;
Create a flag set to false
that changes to true
if any input has a value / changes are made etc.
Then use window.onbeforeunload
and check the value of that flag. If it is true
then show a message, false
and return null
so no warning is shown.
The following example should work all the way back to IE9 and fire a warning before allowing navigation.
I would encourage you to implement this anyway - it is just as easy to accidentally close the page, hit the physical back button etc. by mistake so doing this protects against all accidental navigation.
var changed = false; // change it to true if an input has a value / has changed.
window.onbeforeunload = function() {
return changed ? "Are you sure you want to navigate away? Unsaved changes will be lost." : null;
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…