From fb1ee829eeb5d7d7b881937194c252facc023063 Mon Sep 17 00:00:00 2001 From: Daniel Stock Date: Wed, 29 May 2024 22:05:48 +0200 Subject: [PATCH] smart url loading with a fallback strategy, fixes #4 --- main.js | 32 ++++++++++++++++++++++---------- 1 file changed, 22 insertions(+), 10 deletions(-) diff --git a/main.js b/main.js index 837bc7b..b83faee 100644 --- a/main.js +++ b/main.js @@ -96,30 +96,41 @@ async function createWindow() { }); // show black window - // win.setKiosk(true); + win.setKiosk(true); win.show(); - // load actual page from config file + // Load page from config file if (config != undefined && 'url' in config) { testAndLoadUrl(config.url); + } else { + try { + // Load file from data folder if available + fs.accessSync('/assets/data/index.html'); + win.loadFile('/assets/data/index.html'); + } catch { + // Load fallback page + win.loadFile('index.html'); + } } - // load fallback page - // win.loadFile('index.html'); } /** * 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 + * @returns `true` if the url is allowed, `false` otherwise */ + function validateDomain(event) { - console.log(event.type); - if (config == undefined) return; + if (config == undefined) return true; let url = new URL(event.url); + // allow local urls + if (['file:', 'file'].includes(url.protocol)) return true; + if ('allowedDomains' in config && !config.allowedDomains.includes(url.hostname)) { event.preventDefault(); log.info("Navigation to " + event.url + " prevented"); @@ -137,11 +148,11 @@ function validateDomain(event) { function testAndLoadUrl(testurl) { try { let url = new URL(testurl); - - // It’s an online url, test if it’s reachable + // If it’s an online url, test whether it’s reachable + let delay = 1; if (['https:', 'http:', 'https', 'http'].includes(url.protocol)) { (async function () { - for await (const startTime of setInterval(1000)) { + for await (const startTime of setInterval(delay)) { let reachable = linkExists(url.hostname); if (reachable) { log.info("Successfull access to " + url.hostname) @@ -150,7 +161,8 @@ function testAndLoadUrl(testurl) { // break the interval break; } else { - log.warn("Could not reach " + url.hostname) + log.warn("Could not reach " + url.hostname); + delay = 1000; } } })();