Easy way to load local html file in electron

前端 未结 2 1154
孤独总比滥情好
孤独总比滥情好 2020-12-16 07:36

I\'ve been trying to convert a small webapp into an electron application. It\'s working perfectly, except I need to load a bunch of files (.html) into the main DOM. In the w

相关标签:
2条回答
  • 2020-12-16 08:24

    On the Electron side you will have this code starting with the electron library. With ES6 destructuring you can pull the app property off. The app object represents the overall running process on your machine.

    const electron = require('electron');
    const { app } = electron;
    

    Then you want to add on an event handler:

    app.on('ready', () => {
          console.log('app is ready');
    });
    

    Once you have this running successfully. You have pulled the app property which is the underlying process. You have successfully added your event based function using the app object.

    So you then want to create a new browser window to show content to the user, you pull off another property called BrowserWindow, pass it an empty object with your configuration.

    const electron = require('electron');
    const { app, BrowserWindow } = electron;
    
    app.on('ready', () => {
      const mainWindow = new BrowserWindow({width: 800, height: 600});
    });
    

    You can then load the HTML document by calling the method loadURL() passing ES6 template string:

    const electron = require('electron');
    const { app, BrowserWindow } = electron;
    
    app.on('ready', () => {
      const mainWindow = new BrowserWindow({width: 800, height: 600});
      mainWindow.loadURL(`file://${__dirname}/index.html`);
    });
    
    0 讨论(0)
  • 2020-12-16 08:38

    In Electron you can do it with fs.readFile

    So :

    const fs = require('fs');
    const { promisify } = require('util');
    const path = require('path');
    const readFile = promisify(fs.readFile);
    
    async function loadHTML(html){
        const render = await readFile(path.join(__dirname, html), 'utf-8');
        const parser = new DOMParser();
        const childrenArray = parser.parseFromString(render,'text/html').querySelector('body').childNodes;
        const frag = document.createDocumentFragment();
        childrenArray.forEach(item => {
            frag.appendChild(item);
        });
        document.body.appendChild(frag);
    };
    
    loadHTML('/path/to/my/index.html');
    

    If I don't have a Typo, it should work. it reads the file as a string so you need to parse this String with the DOMParser.

    0 讨论(0)
提交回复
热议问题