const { app, BrowserWindow } = require('electron/main'); const path = require('node:path'); const fs = require('fs'); const log = require('electron-log/main'); //------------------------------------------------------------------------------ // Properties //------------------------------------------------------------------------------ let config; let win; //------------------------------------------------------------------------------ // Function //------------------------------------------------------------------------------ /** * Loads a config file from disc. * The file is expected to be in the application path and called “config.json”. */ function loadConfig() { try { const data = fs.readFileSync(path.join(__dirname, "config.json"), { encoding: 'utf8' }); config = JSON.parse(data); } catch (err) { if (err.code == 'ENOENT') { console.warn('No config file found at ' + path.join(__dirname, "config.json")); } else { console.error(err); } } } /** * Creates the browser window */ async function createWindow() { win = new BrowserWindow({ width: 1920, height: 1080, backgroundColor: '#000000', icon: 'images/icon-512.png', webPreferences: { preload: path.join(__dirname, 'preload.js'), nodeIntegration: true, webSecurity: false, }, show: false, autoHideMenuBar: true }); win.on("closed", function () { win = null; }); win.webContents.addListener("willnavigate-", validateDomain); win.once("ready-to-show", () => { win.setKiosk(true); win.show(); }); win.loadFile('index.html'); if (config != undefined) { try { let url = new URL(config.url); // let options = { // method: 'HEAD', // host: url.hostname, // port: url.port ? url.port : 80, // path: '/' // }; // let req = http.request(options, function (r) { // log.info(r.headers); // }); // req.end(); win.loadURL(config.url); } catch (err) { log.error(err); } } } /** * Validates the url of a navigatio event against the list of allowed domains in * the config file. See https://www.electronjs.org/docs/latest/api/web-contents#event-will-frame-navigate * @param {Event} event */ function validateDomain(event) { let url = new URL(event.url); if ('allowedDomains' in config && !config.allowedDomains.includes(url.hostname)) { event.preventDefault(); log.info("Navigation to " + event.url + " prevented"); } } //------------------------------------------------------------------------------ // Init electon app //------------------------------------------------------------------------------ app.whenReady().then(() => { loadConfig(); log.initialize(); if (config != undefined && 'logPath' in config) { log.transports.file.resolvePathFn = () => config.logPath; } createWindow(); app.on('activate', () => { if (BrowserWindow.getAllWindows().length === 0) { createWindow(); } }) }); app.on('window-all-closed', () => { app.quit() });