How to call a JavaScript function on a web page rendered by Electron?
I have solved the problem. Here's the example code:
...
app.on('ready', function() {
...
mainWindow.webContents.on('did-finish-load', function() {
mainWindow.webContents.executeJavaScript("alert('Hello There!');");
});
...
});
First of all, you should clearly see the differentiation of processes within Electron (formerly Atom Shell). Electron makes use of the main process as a sort of a back-end (you might call it "server side" as you do) and an entry point of your application. As you probably understand the main process can spawn multiple instances of BrowserWindow
, which are actually separate operating system windows each hosting a Chromium rendered web page run in a separate process called renderer process. You can think of renderer process as a simple browser window with potentially extended capabilities, like accessing Node.js modules (I write "potentially", because you can turn off Node.js integration for renderer process).
It should be mentioned that while you have a window with GUI for renderer process, you have none for the main process. In fact, it doesn't make a lot of sense to have one for the back-end logic of your app. So, it is not possible to call alert()
directly in the main process and see the alert window. The solution that you proposed shows the alert indeed. But it's important to understand that the pop up is created by the renderer process and not the main process itself! The main process just asks the renderer to show the alert (that's what webContents.executeJavaScript
function actually does).
Secondly, as I understand what you're really trying to achieve here with calling alert()
function in the main process is the tracing of program execution. You can call console.log()
to output the desired message to console. In this case the application itself must be started from the console:
/path/to/electron-framework/electron /your/app/folder
Now, what's even better is that you can debug the main process. In order to do that the application must be started with the --debug
(or --debug-brk
) key and the value of the listening port assigned to it. Just like that:
/path/to/electron-framework/electron --debug=1234 /your/app/folder
You can use any kind of V8 debugger to attach to the assigned port and start the debugging. That means that theoretically any Node.js debugger must work. Take a look at node-inspector
or WebStorm debugger. There's a popular question here at StackOverflow about debugging Node.js apps: How do I debug Node.js applications?.