#window.electronAPI in renderer, best practice?

17 messages · Page 1 of 1 (latest)

meager spruce
#

Hey folks, I am coming from Electron v0 up to Electron v21, so the preload system is quite a change for me. I've managed to have typed "window.electronAPI", by defining a preload.d.ts. However I am a bit worried about calling "window.electronAPI" everywhere in the renderer process. The types are correct, but I am not fond on relying on a global object. Do you have a best practice for this? Is it ok to have "window.electronAPI" a million times in my application ?

somber willow
meager spruce
#

That's indeed how I do it, by the way in "preload.ts" I do "export ElectronAPI = typeof electronApi", which avoids rewriting the types for nothing

#

however, this means that in the code you will have calls to "window.electronAPI"

#

while for client/server communication, I am more used to writing a client-side service that communicates with the backend

#

and encapsulates the HTTP call

#

the "preload" system forces the use of a global variable tied to window which is a bit unsettling, I wonder if people are ok with calling "window" everywhere in their frontend code

somber willow
#

so?

#

preload expose api into window object

#

you may not use window directly

#

if js able to find proper context

meager spruce
#

Yeah I mean it's not a big deal, just new to me when not being used to Electron

#

I think I will use a bit of nesting to have a nicer structure, instead of putting everything in "electronAPI" object at top level

#

eg "electronAPI = { ui: { zoom: { /* all my zoom related methods*/ }, dialogs: { /** all my dialog related methods */ }}"
etc.

#

By any chance, do you have an idea about what could cause this issue?
The migration to "preload.js" seems done, I don't have imports of electron in my renderer anymore, but this error is quite vague

somber willow
meager spruce
#

hmm this doesn't fix but changes the error message, at least the preload script is running ok