Javascript 如何访问电子中的DOM元素?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32780726/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to access DOM elements in electron?
提问by ant_1618
I am trying to add functionality to a button in index.html
file is as follows:
I have a button element in index.html
我正在尝试向index.html
文件中的按钮添加功能如下:我有一个按钮元素index.html
<button id="auth-button">Authorize</button>
In main.js
of the app, I have
在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;
});
});
But an error occurs as follows:
Uncaught Exception: ReferenceError: document is not defined
但是出现如下错误:
Uncaught Exception: ReferenceError: document is not defined
Can the DOM objects be accessed while building electron apps? or is there any other alternative way that can give me the required functionality?
在构建电子应用程序时可以访问 DOM 对象吗?或者有没有其他替代方法可以为我提供所需的功能?
回答by ROAL
DOM can notbe accessed in the main process, only in the renderer that it belongs to.
DOM不能在主进程中访问,只能在它所属的渲染器中访问。
There is an ipc
module, available on main processas well as the renderer processthat allows the communication between these two via sync/async messages.
有一个ipc
模块可用于主进程和渲染器进程,允许通过同步/异步消息在这两者之间进行通信。
You also can use the remotemodule to call main process API from the renderer, but there's nothing that would allow you to do it the other way around.
您还可以使用远程模块从渲染器调用主进程 API,但没有任何方法可以让您以相反的方式执行此操作。
If you need to run something in the main process as a response to user action, use the ipc
module to invoke the function, then you can return a result to the renderer, also using ipc
.
如果您需要在主进程中运行某些内容作为对用户操作的响应,请使用ipc
模块来调用该函数,然后您可以将结果返回给渲染器,也可以使用ipc
.
Code updated to reflect actual (v0.37.8) API, as @Wolfgang suggested in comment, see edit history for deprecated API, if you are stuck with older version of Electron.
代码更新以反映实际 (v0.37.8) API,正如@Wolfgang 在评论中所建议的,如果您坚持使用旧版本的 Electron,请参阅已弃用 API 的编辑历史记录。
Example script in index.html
:
示例脚本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');
});
And in the main process:
在主要过程中:
var ipc = require('electron').ipcMain;
ipc.on('invokeAction', function(event, data){
var result = processData(data);
event.sender.send('actionReply', result);
});
回答by cuixiping
You can use webContents.executeJavaScript(code[, userGesture, callback])API to execute JavaScript code.
您可以使用webContents.executeJavaScript(code[, userGesture, callback])API 来执行 JavaScript 代码。
for example:
例如:
mainWindow.loadUrl('file://' + __dirname + '/index.html');
mainWindow.webContents.on('did-finish-load', ()=>{
let code = `var authButton = document.getElementById("auth-button");
authButton.addEventListener("click",function(){alert("clicked!");});`;
mainWindow.webContents.executeJavaScript(code);
});
回答by onmyway133
As stated in this tutorial:
如本教程所述:
In Electron, we have several ways to communicate between the main process and renderer processes, such as ipcRenderer and ipcMain modules for sending messages, and the remote module for RPC style communication.
在 Electron 中,我们有多种方式在主进程和渲染器进程之间进行通信,例如用于发送消息的 ipcRenderer 和 ipcMain 模块,以及用于 RPC 样式通信的远程模块。
So you can follow the example in https://github.com/electron/electron-api-demos. You should have a js
file for each html
. In that js
file, you can use require
anytime you want.
因此,您可以按照https://github.com/electron/electron-api-demos 中的示例进行操作。您应该js
为每个html
. 在该js
文件中,您可以require
随时使用。
Code in renderer.js
:
代码renderer.js
:
const ipc = require('electron').ipcRenderer
const asyncMsgBtn = document.getElementById('async-msg')
asyncMsgBtn.addEventListener('click', function () {
ipc.send('asynchronous-message', 'ping')
})
ipc.on('asynchronous-reply', function (event, arg) {
const message = `Asynchronous message reply: ${arg}`
document.getElementById('async-reply').innerHTML = message
})
Code in ipc.html
:
代码ipc.html
:
<script type="text/javascript">
require('./renderer-process/communication/sync-msg')
require('./renderer-process/communication/async-msg')
require('./renderer-process/communication/invisible-msg')
</script>