Importing Custom JavaScript Into an Electron App


#1

I have JavaScript in assets/js/builder.js in my Electron app directory that I would like to import into my main.js Electron file. None of the imports that I’m trying are working through, and I haven’t found many examples on the web. I’ve seen in one place that Electron uses ES6 style imports, but have not been able to get that to work. Am I trying to do something that I shouldn’t?

What I’m trying to do is tie a button in index.html and a hotkey defined in main.js to the same function. I’m registering a global shortcut in main.js, which fires an event when the key is pressed, but I can’t figure out how to get that to use the same function that’s used for the button press in index.html (and it’s js code). I’m very new to Electron, so I may be going about this the wrong way.


#2

I assume that this main.js is your Electron JS creating your BrowserWindow, in which case, you can fire off some JS in that browser window using whateverYourBrowserWindowIsCalled.webContents.executeJavaScript("console.log('Hello from Electron');");

However, if you want a two-way connection between your main and renderer processes, you can use the IPC modules. https://github.com/electron/electron/blob/master/docs/api/ipc-main.md https://github.com/electron/electron/blob/master/docs/api/ipc-renderer.md

It’s also possible to set your keyboard shortcuts from the renderer, meaning you can use the functions present in your BrowserWindow, without having to communicate between the two.

I’m not really sure what you’ve tried, so if I’ve not really answered your question, a code sample of what you’ve tried might help me out!


#3

Thank you for the response, it was very helpful. I decided to use executeJavaScript because I hadn’t tried that yet, and I don’t need two-way communication (yet). It worked great.