Skip to content
Advertisement

Setting OS Specific Keybindings – Cmd on Mac and Ctrl on Everything Else

When configuring Ace (the text editor), you can use OS specific keybindings, like {win: "Ctrl-Esc", mac: "Cmd-Esc"}. This shows that you can have OS specific keybindings in JavaScript, but how is it done?

I would like to create shortcuts that use Cmd on OS X and Ctrl on other systems.

Advertisement

Answer

Unfortunately at this time there is no JavaScript API for detecting if the host OS uses the Ctrl key or the Cmd key for keyboard shortcuts. The only way to determine this is to use platform sniffing.

This is usually done though the use of the navigator.platform property. In fact, the library you mention, Ace editor, actually does it this way. This property also has the advantage that it will not change if you change the user-agent string (at least not normally). On macOS, navigator.platform returns a string like MacProcessor, or MacIntel on an Intel-based Mac.

It’s technically deprecated though (but not likely to be removed any time soon), and some browsers have implemented a newer navigator.userAgentData.platform property in secure contexts only (takes the form of macOS on macOS).

With this knowledge, we can craft a regular expression that will match whichever property is available. Something like the following should be safe and future-proof.

/mac/i.test(navigator.userAgentData ? navigator.userAgentData.platform : navigator.platform);

Now we just need to use the boolean return value from this statement, to determine if our shortcut key should be e.metaKey, or e.ctrlKey.

Working Example:

var isMac = /mac/i.test(navigator.userAgentData ? navigator.userAgentData.platform : navigator.platform);

window.addEventListener('keydown', function(e) {
    if (e.keyCode === 67 && (isMac ? e.metaKey : e.ctrlKey)) {
        document.getElementById('textarea').value += 'Thanks ' + (isMac ? 'Mac' : 'Non-Mac') + '!n';
    }
});
<p>Press <kbd>Cmd</kbd> + <kbd>C</kbd> on Mac, or <kbd>Ctrl</kbd> + <kbd>C</kbd> on everything else.</p>

<textarea id="textarea" style="width: 100%; height: 100px;" placeholder="Click me then use shortcut keys."></textarea>

Alternately:

You might also consider just allowing the user to use either shortcut on any platform.

Working Example:

window.addEventListener('keydown', function(e) {
    if (e.keyCode === 67 && (e.metaKey || e.ctrlKey)) {
        document.getElementById('textarea').value += 'Thanks!n';
    }
});
<p>Press <kbd>Cmd</kbd> + <kbd>C</kbd> or <kbd>Ctrl</kbd> + <kbd>C</kbd>.</p>

<textarea id="textarea" style="width: 100%; height: 100px;" placeholder="Click me then use shortcut keys."></textarea>
Advertisement