Prevent BACKSPACE from navigating back with jQuery (Like Google's Homepage)

前端 未结 9 966
陌清茗
陌清茗 2020-11-30 22:48

Notice while on Google\'s homepage, with no focus on any element, pressing BACKSPACE will put the focus into the search toolbar instead of navigating back.

How can I

9条回答
  •  被撕碎了的回忆
    2020-11-30 23:33

    I've tryed many of the code snippets on the internet without satisfyind result. The new browser versions of IE (IE11) and Crome broke my former solution, but here is what works for me with IE11 + Crome + Firefox. The code prevents backspace and the user doesn't lose anything of what he has keyed in in a text field:

    window.addEventListener('keydown', function (e) {
        if (e.keyIdentifier === 'U+0008' || e.keyIdentifier === 'Backspace' || e.keyCode === '8' || document.activeElement !== 'text') {
            if (e.target === document.body) {
                e.preventDefault();
            }
        }
    }, true);
    

提交回复
热议问题