I want to make a page where certain inputs and links have accesskeys attached to them, and I want to inform the user of what key combination they need to press to activate the input or link. Is there a way to automatically get the accesskey key combination of a browser via JavaScript, or do I need to detect which browser it is and then just use a table where I store the key combination that browser uses?
I haven't found any scripts that could automatically detect this (I've looked at the source code for Wikipedia, and they also go by browser name), which I find curious, since most sites seem to recommend feature detection as opposed to browser detection. I would find it weird if accesskeys would be the exception to that.
Also, according to Wikipedia, there's a huge load of different key combinations for accesskeys, so I don't think making an array of combinations and picking the browser's combination would be the best solution for that.
Per HTML5, there is a JS attribute called accessKeyLabel
that should return a string appropriate to the browser, based on the value of the accesskey
attribute.
This may not work across all browsers/versions that you care about, however, in which case you will need a manual browser-sniffing-and-branching fallback. 10–20 such combinations are not a "huge" amount IMHO, and the only reasonable recourse.
Since HTML 5, we've had the accessKeyLabel
property to read the actual keyboard shortcut assigned by the browser. Sadly, browser support is still too low to rely on it, since not only IE and Edge, but also Chrome are currently missing.
I had the exact same problem but required decent browser support, so I implemented a small polyfill to bridge the gap. It tries to detect feature support and if nothing is found, adds a small function that will return the correct modifier keys based on the User-Agent.
Installing the polyfill (less than 1KB):
npm i access-key-label-polyfill
Activation:
import installAccessKeyLabelPolyfill from 'access-key-label-polyfill';
installAccessKeyLabelPolyfill();
Learn more about the polyfill here: https://github.com/tillsanders/access-key-label-polyfill
Usage of the accessKeyLabel
property is simple, with and without the polyfill. Assuming you have a button like this:
<button accesskey="d">Do crazy stuff</button>
You can get the actual shortcut like this:
const label = document.querySelector('#button').accessKeyLabel;
This might return a string like these:
'⌃⌥d' // Chrome on macOS (only works with polyfill)
'⌃⌥d' // Safari on iOS (works without polyfill)
'Alt+Shift+d' // Firefox on Windows (works without polyfill)
'Alt+d' // Edge on Windows (only works with polyfill)
Be aware though, that in cases where the browser does not support accessKeyLabel
(and you're not using the polyfill) or where the browser does not support accessKey
, you will only get undefined
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With