ElectronJS + Vue.js: Setting up ipcRenderer event handlers

When utilizing the ipcRenderer within a Vue.js view component, make sure you register the IPC event handler once for that component using ‘ipcRenderer.on’ in the ‘mounted’ lifecycle event of the Vue.js component.

If you make the mistake of placing the IPC event handler registration (ipcRenderer.on) inside a function that is called more than once within your component, you will notice a strange side-effect. What you will end up experiencing is that each time your function is called, the ipcRenderer will register a new event handler for the named event and each time that event is called you will see the handler executed X-number of times, with X equal to the number of times the function that contains ‘ipcRenderer.on’ has been called within your component.

If you are not careful, this is an easy mistake to make and a time consuming one to figure out.


 mounted: function () {
    this.$nextTick(function () {
        //Register IPC Renderer event handles once for this control
        ipcRenderer.on('name-of-your-event', (e, args) {
            // TODO: Hanlde the event broadcast here
        });
    });
}

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();
    })
}