How to access DOM elements in electron?

DOM can not be accessed in the main process, only in the renderer that it belongs to.

There is an ipc module, available on main process as well as the renderer process that allows the communication between these two via sync/async messages.

You also can use the remote module to call main process API from the renderer, but there’s nothing that would allow you to do it the other way around.

If you need to run something in the main process as a response to user action, use the ipc module to invoke the function, then you can return a result to the renderer, also using ipc.

Code updated to reflect actual (v0.37.8) API, as @Wolfgang suggested in comment, see edit history for deprecated API, if you are stuck with older version of Electron.

Example script in index.html:

var ipc = require('electron').ipcRenderer;
var authButton = document.getElementById('auth-button');
authButton.addEventListener('click', function(){
    ipc.once('actionReply', function(event, response){
        processResponse(response);
    })
    ipc.send('invokeAction', 'someData');
});

And in the main process:

var ipc = require('electron').ipcMain;

ipc.on('invokeAction', function(event, data){
    var result = processData(data);
    event.sender.send('actionReply', result);
});

Leave a Comment