flawy
flawy

Reputation: 67

Get DOM javascript variable from Node.JS in Electron

Just like the title says, how can I get variable from DOM in main.js in electron.

Code:

value.js:

var x = document.getElementById('x');

main.js from ELECTRON:

const {app, BrowserWindow, Menu} = require('electron')

require('./value.js') // include value.js
console.log(x.getValue());

The error says: document is not defined

Upvotes: 0

Views: 2184

Answers (2)

Zenny
Zenny

Reputation: 181

I believe you are looking for interprocess communication. While you can also use remote for some things (It's basically a simplified wrapper of ipcMain and ipcRenderer), I didn't see a way to set a global variable (And I haven't used it myself). Instead, we can use ipcMain and ipcRenderer directly.

For example, you can have the following listeners in your main process:

let ipc = require('electron').ipcMain,
    test = 0;

ipc.on('setTest', (event,arg)=>{
  test = arg; // Beware of any possible user input!
  event.returnValue = test; // Required for sendSync or it hangs forever! You can send back anything here.
});

ipc.on('getTest', (event,arg)=>{
  event.returnValue = test;
});

And on the client side you can use something like:

let ipc = require('electron').ipcRenderer;

ipc.sendSync('setTest', 1);
// and/or
ipc.sendSync('getTest');

EDIT: Since DOM elements are strange objects, you might have to use jQuery to clone it before you can pass it around, or use another method of cloning to make it a JSON object (Or just send what you need in a simpler form). Alternatively, store things on the renderer and communicate when to do things via IPC.

Upvotes: 1

Obsidian Age
Obsidian Age

Reputation: 42304

Depending on how you're loading your JavaScript, you need to place your script before the HTML's </body> closing tag, or in a window.onload JavaScript function, as the document object does not automatically get created when you call document.getElementById.

Upvotes: 0

Related Questions