未定义`document`电子 [英] `document` is not defined Electron
本文介绍了未定义`document`电子的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试使用 fs
模块从文件中读取JSON,并将其显示在ID为 list
的 div
中电子应用程序.我在 index.js
中的代码如下:
I'm trying to read JSON from a file using the fs
module, and display that in a div
with id list
in an Electron app. My code in index.js
looks like this:
dialog.showOpenDialog((filenames) => {
if (!filenames) return;
fs.readFile(filenames[0], (err, data) => {
if (err) {
alert('Could not read file.\n\nDetails:\n' + err.message);
return;
}
let json = JSON.parse(data).en;
for (let i = 0; i < json.length; ++i) {
let html = "<div class='entry'><b>";
// Add more to html variable from json data
$('list').html(html);
}
});
});
我收到一条错误消息:
未捕获的异常:
错误:jQuery需要带有文档的窗口
Error: jQuery requires a window with a document
如何从JS修改DOM,为什么会出现此错误?
How do I modify the DOM from the JS, and why do I get this error?
推荐答案
You can use executeJavascript
method of your BrowserWindow's webContents to execute code directly in Renderer process.
const { app, BrowserWindow} = require('electron')
const path = require('path')
const fs = require('fs')
app.once('ready', () => {
var mainWindow = new BrowserWindow()
mainWindow.loadURL(path.join(__dirname, 'index.html'))
fs.readFile(path.join(__dirname, 'test.json'), 'utf8', (err, data) => {
if (err) {
alert('Could not read file.\n\nDetails:\n' + err.message)
return
}
let json = JSON.parse(data)
for (let i in json) {
mainWindow.webContents.executeJavaScript(`
document.getElementById("list").innerHTML += '<br> ${i}: ${json[i]}'
`)
// can be replaced with
// $('#list').append('<br> ${i}: ${json[i]}')
// if html have jquery support
}
})
})
要在电子中使用jquery,您应该安装 jquery
模块并在HTML中引用
For using jquery in electron you should install jquery
module and refer it in your HTML
<script>window.$ = window.jQuery = require('jquery');</script>
Instructions in detail can be found here
这篇关于未定义`document`电子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文