Right way of loading local html pages into main window?


#1

Hi,

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:

$("#main").load("./views/details.html");

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


#2

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.


#3

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})
win.loadURL(‘https://github.com’)

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


#4

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

So:

`
//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’})
win.loadURL(file://${__dirname}/render/index.html)
})`

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


#5

Hey
Am facing this problem to. Did you solve it!


#7

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 => {
    frag.appendChild(item);
});
document.body.appendChild(frag);

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