Cannot set properties of null (setting 'hidden') of an ids used in preload script

Viewed 27

I am using Electron app with a preload script and I am asigning ids with document.getElementById to vars and then I used that variables in a function. But because it is a preload script some vars are not set because the index file is not loaded fully (i guess). I have tried using window.onload function to wait for the window to fully load but this is not helping. Is there anything else I can do to set the vars correctly?

1 Answers

Preload scripts cannot access the DOM of the page since they're executed before the window completely loads (hence the name) and are meant to only provide interface functions between the strictly sandboxed renderer process (any JS loaded from the HTML loaded by the window) and the unrestricted main process (the one starting your application).

Thus, anything that is supposed to modify your page (the DOM) has to occur in the correct script, i.e. in the renderer's own JavaScript. The preload script is only supposed to load Electron APIs and expose them to the renderer if needed (one by one to minimise the risk vector). I suggest reading Electron's Preload Script Tutorial.

To sum up: Whenever you need access to Electron APIs or need to communicate with your main process, you load the APIs and create functions for the communication in preload.js, exposing them to the renderer process via contextBridge. When you need to use the APIs or need to communicate with your main process, you call these functions from the renderer process.

Also, if you're stuck trying to comprehend Electron's process model (main and renderer process), take a look at Electron's process architecture documentation.

Related