[英]How to call a function in another script from main.js in electron
[英]Electron - passing argument from main.js to html
我想将一个参数从 main.js 进程传递到我在 init 上的 html 站点。
我已经尝试了几件事,但它不起作用。 目标是用“123”填写表单域“用户名”。 我已经用#1 和#2 标记了我为实现这一点而添加的内容。 任何想法,缺少什么? 提前致谢!
主.js
// Modules to control application life and create native browser window
const {app, BrowserWindow, session, ipcMain, webContents} = require('electron')
const path = require('path')
app.commandLine.appendSwitch('disable-features', 'OutOfBlinkCors');
function createWindow () {
// Create the browser window.
const mainWindow = new BrowserWindow({
width: 800,
height: 600,
webPreferences : {
webSecurity: false,
nodeIntegration: true
}
})
// and load the index.html of the app.
mainWindow.loadFile('index.html')
//#1
//Passing arguments
mainWindow.webContents.send('got-access-token', '123');
}
app.whenReady().then(() => {
createWindow()
app.on('activate', function () {
// On macOS it's common to re-create a window in the app when the
// dock icon is clicked and there are no other windows open.
if (BrowserWindow.getAllWindows().length === 0) createWindow()
})
})
渲染器.js
const { ipcRenderer } = require('electron')
//#2
//Pass argument
ipcRenderer.on("got-access-token", (event, accessToken) => {
document.getElementById("username").value = accessToken;
});
html
<!DOCTYPE html>
<html>
<body>
<div class="login">
<h1>Login</h1>
<!-- <form method="post">-->
<input type="text" name="u" placeholder="Username" required="required" id="username"/><script> require("./renderer.js"); </script>
<input type="password" name="p" placeholder="Password" required="required" id="password"/>
<button type="submit" id="login" class="btn btn-primary btn-block btn-large">Login ...</button>
<!-- </form> -->
</div>
<!-- You can also require other files to run in this process -->
<script src="./renderer.js"></script>
</body>
</html>
在你的主要过程中
ipcMain.on('request-token',(event)=>{
event.reply('receive-token', token);
})
在你的渲染器中
在你的主渲染器中
ipcRenderer.on('receive-token',(accessToken)=>{
console.log('token received')
document.getElementById("username").value = accessToken;
});
ipcRenderer.send('request-token');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.