Exercise 1: Hello Electron! (Part 2)
David Neal edited this page May 31, 2018
·
2 revisions
- Launch Visual Studio Code
- Click File -> Open...
- Browse to project folder and click Open
Add a file named main.js
with the following:
const electron = require( "electron" );
const { app, BrowserWindow } = electron;
let mainWindow = null;
app.on( "window-all-closed", () => {
if ( process.platform !== "darwin" ) {
app.quit();
}
} );
app.on( "ready", () => {
mainWindow = new BrowserWindow( { width: 800, height: 600 } );
mainWindow.loadURL( `file://${ __dirname }/index.html` );
mainWindow.on( "closed", () => {
mainWindow = null;
} );
} );
Create a file named index.html
with the following:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Hello Electron</title>
</head>
<body>
<h1>Hello from Electron!</h1>
</body>
</html>
Update the main
and add a "start" script to scripts
.
"main": "main.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "electron ."
},
From the Terminal / Command window, run:
npm run start
The BrowserWindow
has a number of other events, including one named ready-to-show
. This event is fired when the DOM has finished rendering. You can delay showing the window until the DOM has finished to ensure the user does not see any unstyled content. Your code might look something like this:
app.on( "ready", () => {
mainWindow = new BrowserWindow( { width: 800, height: 600, show: false } );
mainWindow.loadURL( `file://${ __dirname }/index.html` );
mainWindow.once( "ready-to-show", () => {
mainWindow.show();
} );
mainWindow.on( "closed", () => {
mainWindow = null;
} );
} );