让我用我当前的设置来回答这个问题:
index.html
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
<h1></h1>
<p>Note One</p>
</body>
<script>
require('./renderer.js')
</script>
</html>
main.js 主流程
const { app, BrowserWindow } = require('electron')
let mainWindow = null
app.on('ready', () => {
mainWindow = new BrowserWindow()
mainWindow.webContents.loadFile('index.html')
})
下面是渲染器,我在其中使用了一些基本的 DOM 方法。有些工作有些失败:
渲染器.js
document.querySelector('p').remove()
const h2 = document.createElement('h2')
h2.textContent = 'test'
renderer.js 的详细信息:
第一行按预期工作,第一个 p
元素被返回并删除。
第二行不会导致任何可见错误,但无法在 DOM 中创建 h2
元素,因此在第 3 行中不会添加任何文本。
我不明白这种行为,为什么我无法访问渲染器进程中的所有 DOM API?
最佳答案
线路document.querySelector('p').remove()
有效,因为 querySelector
返回单个<p>
具有 .remove
的元素方法。
第二行document.createElement('h2')
创建一个新的 <h2>
元素,但显然您没有将其添加到 DOM,因此 GC 将其删除。尝试:
const h2 = document.createElement('h2');
h2.textContent = 'Test createElement';
document.body.appendChild(h2);
看看这是否有效(提示:应该!)。
关于javascript - 无法访问 Electron 渲染器进程中的某些 DOM 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54331433/