在电子文件中加载本地html文件的简单方法 [英] Easy way to load local html file in electron
问题描述
我一直在尝试将小型Web应用程序转换为电子应用程序。它运行正常,只是我需要将一堆文件(.html)加载到主DOM中。在Web应用程序中,我只使用了 $。get
,但是如何在电子中实现呢?我尝试查看DOC,但是除了IPC管道(我不太了解)之外,我找不到简单的方法。
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 webapp, I just used $.get
, but how can I do it in electron? I try looking at the DOC but I cannot find an easy way to do that, beside an IPC pipe (and I don't quite get it).
有人可以指出吗?我会朝着正确的方向前进?
Could anyone point me to the right direction?
编辑
我将在此处进行说明。我有一个启动BrowserWindow的主进程
I'll clarify here. I have a main process that start a BrowserWindow
mainWindow = new BrowserWindow({width: 800, height: 600})
,然后在通过$导入的 js
文件中< script>
标记,我想加载并在对话框中附加一些文件:
and then, in a js
file imported via a <script>
tag, I want to get load and attach some file inside a dialog:
$('.dialog').load('pages/hello.html', {})
亲切的问候
推荐答案
在Electron中,您可以使用 fs.readFile
In Electron you can do it with fs.readFile
所以:
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');
如果我没有错字,那应该可以。
会将文件读取为字符串,因此您需要使用DOMParser解析此字符串。
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.
这篇关于在电子文件中加载本地html文件的简单方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!