What's the proper way to handle forms in Electron?

Elfy picture Elfy · Apr 9, 2017 · Viewed 16.5k times · Source

The form html and submit event is part of the "renderer". The submitted data should be available in the main process. What's the proper way to submit the form and make that data accessible in main.js ?

Should I simply use the "remote" module to pass the data to a function from main.js or is there a better approach?

Answer

Adam Eri picture Adam Eri · Apr 17, 2017

We use a service (Angular) to process form data in a window. Then notify the remote, if needed.


From your renderer you can send data to the ipc, then in your main.js you catch this event and the passed form data:

// renderer.js
let ipcRenderer = require('electron').ipcRenderer;
ipcRenderer.send('submitForm', formData);

// main.js
ipcMain.on('submitForm', function(event, data) {
   // Access form data here
});

You can also send messages back to the renderer from the main.js.

Either sync:

// main.js
ipcMain.on('submitForm', function(event, data) {
   // Access form data here
   event.returnValue = {"any": "value"};
});

Or async:

// main.js
ipcMain.on('submitForm', function(event, data) {
   // Access form data here
   event.sender.send('formSubmissionResults', results);
});

// renderer.js
ipcRenderer.on('formSubmissionResults', function(event, args) {
   let results = args.body;
});