0

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

flawy
  • 57
  • 8
  • 1
    Possible duplicate of [How to access DOM elements in electron?](http://stackoverflow.com/questions/32780726/how-to-access-dom-elements-in-electron) – kawadhiya21 Jan 25 '17 at 04:31

2 Answers2

1

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.

Zenny
  • 181
  • 8
0

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.

Obsidian Age
  • 41,205
  • 10
  • 48
  • 71