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

1

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.