Right way of loading local html pages into main window?



I was looking all around, docs, google, etc., on how to load a html file in the main window, but I can’t find a way.

Is this really this complicated or dead simple? With what I have came up is:


What other ways do exist for loading a file into the same window?


Have you read through the Electron Quick Start guide? It gives an example of how to load the HTML into the window you open on startup.


I have read it, but I need to load the new html file in the renderer process.

I have found a method via remote:

const {BrowserWindow} = require(‘electron’).remote
let win = new BrowserWindow({width: 800, height: 600})

But this opens always a new window, and I need to replace the existing page.


I think that’s the point. Your main process is just that, it manages all of your rendered html, new windows…


//my main.js
const electron = require(‘electron’)
const {app, BrowserWindow} = electron

let win

app.on(‘ready’, () => {
const {width, height} = electron.screen.getPrimaryDisplay().workAreaSize
win = new BrowserWindow({width, height, backgroundColor: ‘#6BD3AB’})

When I run my application, my app looks like file://${__dirname}/render/index.html in my case.


Am facing this problem to. Did you solve it!


I wrote a little render function for this issue. I’m not sure it’s very good practice but it works.
If anyone else has a better Idea, please let me know as well. :slight_smile:

const fs = require(‘fs’);
const { promisify } = require(‘util’);
const path = require(‘path’);
const readFile = promisify(fs.readFile);

Solution 1

const html = 'path/to/my.html' ;
const render = await readFile(path.join(__dirname, html), 'utf-8');
document.body.innerHTML = render;

Solution 2

const html =  `path/to/my.html`;
const render = await readFile(path.join(__dirname, html), 'utf-8');

const parser = new DOMParser();
const childernArray = parser.parseFromString(render,'text/html').querySelector('body').childNodes;

const frag = document.createDocumentFragment;

childrenArray.forEach(item => {

You also can do with “require” - but then your html has to be wrapped in a module.