gpt4 book ai didi

javascript - `document` 没有定义 Electron

转载 作者:行者123 更新时间:2023-11-29 19:03:52 26 4
gpt4 key购买 nike

我正在尝试使用 fs 模块从文件中读取 JSON,并将其显示在 ID 为 listdiv 中 Electron 应用程序。我在 index.js 中的代码如下所示:

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);
}
});
});

我收到一条错误消息:

Uncaught Exception:

Error: jQuery requires a window with a document

如何从 JS 修改 DOM,为什么会出现此错误?

最佳答案

您可以使用 executeJavascript BrowserWindow 的 webContents 方法直接在渲染器进程中执行代码。

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
}
})
})

要在 electron 中使用 jquery,你应该安装 jquery 模块并在你的 HTML 中引用它

<script>window.$ = window.jQuery = require('jquery');</script>

可以找到详细说明here

关于javascript - `document` 没有定义 Electron,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44455356/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com