Explain Codes LogoExplain Codes Logo

How does one capture a Mac's command key via JavaScript?

javascript
event-listeners
keyboard-events
cross-browser-compatibility
Alex KataevbyAlex Kataev·Feb 11, 2025
TLDR

Hinging the Command key on JavaScript through the event.metaKey feature in keydown or keyup event listeners is quite straightforward:

document.addEventListener('keydown', (e) => e.metaKey && console.log('Command key active!')); // Because why not?

The snippet above is a trailblazer for handling the Command key state, setting up your foundation for yet more intricate key scenarios.

Enhanced detection

Broadening the scope beyond just capturing the Command key, the event.key and event.code properties allow us to pinpoint whether the MetaLeft or MetaRight was triggered, whilst skirting deprecated holdovers like keyCode.

document.addEventListener('keydown', (event) => { if(event.metaKey){ console.log(event.code); // Because Left and Right deserve equal love! } });

The above code determines specific key presses in keyboards sporting both left and right Command keys, enhancing precision.

Cross-browser compatibility

While the Command key stands in the spotlight, bear in mind it might march to different drummers across varied browsers, Safari in particular. Rigorous testing should not be neglected and variations addressed accordingly to achieve universal appeal.

Platform variance

A discrepancy to note when porting this between systems: while the event.key is 'Meta' during a Command key press on a Mac, this behaviour is not ubiquitous. As developers, it's our duty to ensure seamless functionality no matter the environment.

Real-world application

Now let's put theory into practice and stitch together keyboard shortcuts for a web app on macOS. Let's say the Command-N combo initiates a new document.

document.addEventListener('keydown', (event) => { if (event.metaKey && event.key === 'n') { event.preventDefault(); // Friends don't let friends trigger browser shortcuts createNewDocument(); // Mass production of documents at your fingertips console.log('Access code to new documents: "n"'); } });

You'll note, we "opted out" of triggering native browser shortcuts during application-specific keyboard events by invoking event.preventDefault().

Usable by Design

When working with editable elements like <input> or <textarea>, ensure your keyboard handlers don't impede regular typing. Introduce checks to bypass these elements when needed.

document.addEventListener('keydown', (event) => { if (event.target.tagName !== 'INPUT' && event.target.tagName !== 'TEXTAREA' && !event.target.isContentEditable) { // Hey text, can I join you? } });