How does Google Sheets override browser shortcuts? - javascript

I'm creating a complicated in-browser app and I'd like to use some keyboard shortcuts that are currently used by Chrome and/or the other major browsers. I searched online and couldn't find a way to override browser shortcuts, but I saw that Google Sheets has just the kind of functionality I want: a user can select an option to override browser shortcuts.
How does Google sheets make this work?
Update: To clarify, since this has gotten some downvotes: I'm aware of event.preventDefault(). The problem is that it does not seem to work for key combinations like Ctrl + t (open new tab).

The general idea is to intercept the event and call event.preventDefault() on it if it corresponds to a shortcut that you want to override. For example, the following code will prevent you from navigating to your leftmost tab if you press control-1:
document.body.addEventListener('keydown', (event) => {
// keyCode 49 corresponds to the "1" key
if(event.keyCode==49 && event.ctrlKey) {
event.preventDefault();
console.log('default action prevented, doing custom action instead');
}
});
body {
background-color: yellow;
}
click me first
Repeat for as many keyCodes and modifiers as you want.

Related

Keyboard and mouse events # Accessbility

How to write conditions for an automatic mouse click in the UI when we press any key on the keyboard.
I'm Working on the Accessibility Part ->
My Scenario is we are having banner which is displayed when the page loads initially. for that until we close that banner the focus should be inside that banner.
I have tried the onKeyDown event. when we trigger the onKeyDown event by using e.preventDefault() the focus is hidden. I need to get that focus again when I click any key on the keyboard.
Thanks in Advance.
handleTab = (e) => {
let tabKey = false
if (e.keyCode === 9) {
e.preventDefault()
tabKey = true
}
if(tabKey) {
# here I need an automatic browser click event. so that when I hit the tab key it will go inside of that banner
}
onKeyDown = {this.handleTab()}
Try to use tabindex property to prevent tab navigation outside the banner.
<input type="text" tabIndex="-1"/>
I created small demo to test: https://codepen.io/mich_life/pen/vYRMpqe
This is what the MDN documentation has to say about keyCode:
Deprecated: This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the compatibility table at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.
key which is a textual representation of the pressed key should be used instead & has been supported since Internet Explorer 9.
Since you haven't specified, if the banner is inside or outside your component, I am going by outside.
handleTab=(evt)=> {
if(evt.key == 'Tab') {
evt.preventDefault();
document.getElementById('banner').focus();
}
}
If it's rendered inside your component, use a ref instead.

JavaScript, Chrome, Textbox, Space, Backspace

I'm writing code in JavaScript, targeting Chrome.
Now, consider what happens when:
I press Space/Backspace on a webpage vs
I press Space/Backspace on a textbox
BY using (goog.events.listen js/document.body ...) I can listen for Space/Baskspace events and react on them. However, the browse still processes them i.e. when I press Space the browser still scrolls down and when I press Basckspace, the browser goes to the previous webpage.
I would like to prevent this "default behavior" -- i.e. I want to process the Space/Backspace events, and I want the browser to ignore them.
Thanks!
Return false from the event handler to cancel the event.
document.body.onkeydown = function killSpace(e) {
if (e.keyCode === 32) {
return false;
}
};
Please don't kill keyboard shortcuts globally like this. It hurts usability. Only prevent default behaviour when some custom widget on the page has focus, and this element can lose focus using a keyboard shortcut like tab.

How Google Doc intercepts Ctrl - S / Command - S to save the document not the html page

I am trying to introduce this into my project, I did some search but here https://github.com/RobertWHurst/KeyboardJS/issues/19 I found that it looks quite hard to intercept these meta keys.
So I am curious how google doc does that? Is it a different way from using just javascript?
It's not difficult at all. You just bind to document and listen for keydown: http://jsfiddle.net/zerkms/DVmDs/ (just assume your document is the bottom right block and click it once before you press ctrl+s)
$(document).on('keydown', function(e) {
if (e.keyCode == 83 && e.ctrlKey) {
alert('you have pressed ctrl+s');
}
});​
What have you tried?
Here's a fiddle (that I found in google, took me about 10 seconds) that is intercepting those events using common methods:
http://jsfiddle.net/GBuBj/
taken from here: http://www.scottklarr.com/topic/126/how-to-create-ctrl-key-shortcuts-in-javascript/
and here: https://superuser.com/questions/120672/mediawiki-assign-ctrl-s-to-save-page-edit-mode
Win key is different story, but CTRL is fine (except maybe CTRL+ESC and couple of similar shortcuts that are used by OS).

Prevent default event action not working...?

I'm trying to add keyboard shortcuts on my website to make fast navigation possible using the keyboard. I'm running into a slight problem, however, with my attempted Alt+X shortcut. The event runs just fine and returns false as it should, but the browser's File menu comes up regardless. I've also tried the preventDefault method, but no change.
The cut-down version of the script is:
document.documentElement.onkeydown = function(e) {
e = e || window.event;
switch( e.keyCode || e.which) {
// some cases here - most notably:
case 116: // F5 key
if( activeFrame) {
activeFrame.contentWindow.location.reload();
// reloads an iframe if one is active
return false;
}
break;
// more cases...
case 88: // X key
if( e.altKey) {
// do something
return false;
}
}
}
As noted above, overriding the default action of the F5 key works just fine - the browser reloads the page only if no iframe is active. I don't quite see how to prevent the menu from appearing when Alt+X is pressed.
use stopPropagation(e); instead of preventDefault method
function stopPropagation(e)
{
e = e || event;/* get IE event ( not passed ) */
e.stopPropagation? e.stopPropagation() : e.cancelBubble = true;
}
Reference link
Another SO question which mentions that preventDefault has issue in IE.
UPDATE
Try using below code as per MSDN Reference
event.returnValue=false;
And some point from Detecting keystrokes
Some general caveats:
Generally, Mac is less reliable than Windows, and some keys cannot be detected.
Explorer doesn't fire the keypress event for delete, end, enter, escape, function keys, home, insert, pageUp/Down and tab.
Onkeypress, Safari gives weird keyCode values in the 63200 range for delete, end, function keys, home and pageUp.Down. The onkeydown and -up values are normal.
Alt, Cmd, Ctrl and Shift cannot be detected on Mac, except in Opera. However, you can always use the altKey, ctrlKey, and shiftKey properties.
I actually had a web app working just fine with CTRL shortcut keys, but then decided I'd be clever and use the accesskey attribute, and ran into this exact issue with IE.
The problem with going to CTRL shortcut keys is that many of those are more standard/useful across many applications (eg: cut, copy, paste, select all).
Ctrl+Alt is fairly safe, but requires more work on the user's part.
I tend to just try to stick to ALT shortcuts IE doesn't stubbornly insist on handling.
Demo of CTRL + A/CTRL + F being cancelled successfully:
http://jsfiddle.net/egJyT/
This answer seems to imply it isn't possible to disable the menu shortcuts without putting IE into kiosk mode.
Beware that if you manage to successfully prevent the browser from detecting a key combination you may make your page unusable for some users. Many screen readers have reserved almost any key you can think of to control the screen reader and if your page was accessible using a screen reader before you added the shortcut key code, it may be completely un-accessible users needing screen readers after you add it.
Read this article about access keys (a bit old but probably still relevant), and this article about Reserved Keystroke Combinations before you invest too much time on this problem.

Prototype observe event problem in Opera

I'm using Prototype and doing Event.observe on window.document.
I'm catching enter (keyCode 13) and alt+f (altKey && keyCode=70).
My code is working super with firefox, IE and chrome. With Opera no. Enter is catched, but only if my focus is not in any text input. Alt+F is not working at all.
Is it bug in Prototype or I need to do something 'extra' on Opera in order to go on? As i said, in all other browser my code works....
Firstly, the following is a helpful resource: http://unixpapa.com/js/key.html
Secondly, you should know there is a difference between keydown (or keyup) and keypress. keypress does not typically allow modifier keys, though it does allow some in Opera like control. Better to use keydown for cross-browser consistency.
I get keyCode === 13 in Opera 11.10 no matter whether the textbox is entered or not, and no matter whether using Prototype like this:
Event.observe(document, 'keydown', function (e) {
alert(e.charCode+'::'+e.keyCode);
});
or using the native method directly (using attachEvent for IE):
if (document.addEventListener) {
document.addEventListener('keydown', function (e) {
alert(e.charCode+'::'+e.keyCode);
}, false);
}
else { // IE
document.attachEvent('onkeypress', function (e) {
alert(e.charCode+'::'+e.keyCode);
});
}
However, alt is indeed not detected inside a textbox unless combined with a control or function key (though that doesn't work in Chrome or IE). This may be because Windows uses alt to give access to the applications menu bar.
You could try using control key and using preventDefault() (to avoid default behaviors like ctrl-f doing a page find) though this might annoy your users who might not want their browser behaviors disabled for your page.
Alt-F activates the menu and Opera doesn't let JavaScript handle this key press.

Categories