Electron JS: Handle CMD+Q in OS X

When creating an Electron desktop application you will find that it does not, out of the box, support the traditional keyboard shortcut CMD+Q to close your application when running on OS X. To solve this situation, you simply need to import the ‘globalShortcut’ object from Electron, check for OS X ‘Darwin’, add a listener for the key combination, and when that combination is hit quit the application.

If you are using the Electron template code for your Main.js file (might be different if you are using custom code, but you can figure it out easy), here is what you need to do:

  1. Add ‘globalShortcut’ to your electron library import statement
const {app, BrowserWindow, Menu, globalShortcut} = require('electron');
  1. In your ‘createWindow’ function, add the following code to check for OS X ‘Darwin’ and add a listener to the CMD+Q key combination that executes the ‘quit’ function on the application
if (process.platform === 'darwin') {
    globalShortcut.register('Command+Q', () => {
        app.quit();
    })
}

Published by

Tim Clark

Experienced Business Owner, Chief Information Officer, Vice President, Chief Software Architect, Application Architect, Project Manager, Software Developer, Senior Web Developer, Graphic Designer & 3D Modeler, University Instructor, University Program Chair, Academic Director. Specialties: Ruby, Ruby on Rails, JavaScript, JQuery, AJAX, Node.js, React.js, Angular.js, MySQL, PostgreSQL, MongoDB, SQL Server, Responsive Design, HTML5, XHTML, CSS3, C#, ASP.net, Project Management, System Design/Architecture, Web Design, Web Development, Adobe CS6 (Photoshop, Illustrator)

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s