Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the browser+platform keyboard modifiers

I am creating a Web app that should be completely operated through the keyboard. I must provide the user the accesskey combination for different buttons, but the way accessing them is different for each browser and platform. E.g. For Chrome or Firefox in Ubuntu, if the accesskey is "d", I must press:

SHIFT+ALT+d

But if I access from Firefox 13 or older, I must use:

CTRL+d

So,the way to activate the accesskey depends on the browser and its platform.

I would like to know if there is a way to automatically detect which are those modifiers (SHIFT+ALT or CTRL) so I can properly update the instructions for the users according to their platform and browser.

TIA!

like image 372
gal007 Avatar asked Jul 09 '20 00:07

gal007


1 Answers

Just use accessKeyLabel:

const btn = document.getElementById("btn"),
keyCombParagraph = document.getElementById("key-comb");

{
  const label = btn.accessKeyLabel;
  keyCombParagraph.innerHTML = label ?
    `This button can be activated by pressing ${label}.` :
    `This button doesn't have an assigned access key.`;
}

btn.addEventListener("click", () => {
  alert("Hello.");
});
<button id="btn" accesskey="h">Hello</button>
<p id="key-comb"></p>

Note that the spec does not define a format for accessKeyLabel and contains the following note:

Browsers on different platforms will show different labels, even for the same key combination, based on the convention prevalent on that platform. For example, if the key combination is the Control key, the Shift key, and the letter C, a Windows browser might display "Ctrl+Shift+C", whereas a Mac browser might display "^⇧C", while an Emacs browser might just display "C-C". Similarly, if the key combination is the Alt key and the Escape key, Windows might use "Alt+Esc", Mac might use "⌥⎋", and an Emacs browser might use "M-ESC" or "ESC ESC".

In general, therefore, it is unwise to attempt to parse the value returned from the accessKeyLabel IDL attribute.

like image 192
D. Pardal Avatar answered Oct 08 '22 20:10

D. Pardal