我正在尝试向 index.html
文件中的按钮添加功能,如下所示:
我在 index.html
<button id="auth-button">Authorize</button>
在应用程序的 main.js
中,我有
require('crash-reporter').start();
console.log("oh yaeh!");
var mainWindow = null;
app.on('window-all-closed', function(){
if(process.platform != 'darwin'){
app.quit();
}
});
app.on('ready',function(){
mainWindow = new BrowserWindow({width:800, height : 600});
mainWindow.loadUrl('file://' + __dirname + '/index.html');
var authButton = document.getElementById("auth-button");
authButton.addEventListener("click",function(){alert("clicked!");});
mainWindow.openDevTools();
mainWindow.on('closed',function(){
mainWindow = null;
});
});
但是出现如下错误:
未捕获的异常:ReferenceError:文档未定义
在构建 Electron 应用程序时可以访问 DOM 对象吗?还是有任何其他替代方法可以为我提供所需的功能?
最佳答案
DOM 不能在主进程中访问,只能在它所属的渲染器中访问。
有一个 ipc
模块,在 main process 上可用以及 renderer process允许这两者之间通过同步/异步消息进行通信。
您还可以使用 remote模块从渲染器调用主进程 API,但没有任何东西可以让您以相反的方式进行。
如果您需要在主进程中运行一些东西作为对用户操作的响应,请使用 ipc
模块调用该函数,然后您可以将结果返回给渲染器,也可以使用 IPC
.
代码已更新以反射(reflect)实际 (v0.37.8) API,正如@Wolfgang 在评论中建议的那样,如果您坚持使用旧版本的 Electron,请查看已弃用 API 的编辑历史。
index.html
中的示例脚本:
var ipc = require('electron').ipcRenderer;
var authButton = document.getElementById('auth-button');
authButton.addEventListener('click', function(){
ipc.once('actionReply', function(event, response){
processResponse(response);
})
ipc.send('invokeAction', 'someData');
});
在主进程中:
var ipc = require('electron').ipcMain;
ipc.on('invokeAction', function(event, data){
var result = processData(data);
event.sender.send('actionReply', result);
});
关于javascript - 如何访问 Electron 中的DOM元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32780726/