简体   繁体   English

Electron - 将参数从 main.js 传递到 html

[英]Electron - passing argument from main.js to html

I would like to pass an argument from main.js process to my html site on init.我想将一个参数从 main.js 进程传递到我在 init 上的 html 站点。

I've tried several things, but it doesn't work.我已经尝试了几件事,但它不起作用。 The goal is, to fill the formfield "username" with "123".目标是用“123”填写表单域“用户名”。 I have marked, what I have added to realize this with #1 and #2.我已经用#1 和#2 标记了我为实现这一点而添加的内容。 Any ideas, whats missing?任何想法,缺少什么? thanks in advance!提前致谢!

Main.js主.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()
  })
})

Renderer.js渲染器.js

const { ipcRenderer } = require('electron')
//#2
//Pass argument 
ipcRenderer.on("got-access-token", (event, accessToken) => {
    document.getElementById("username").value = accessToken;
});

html 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>

In your main process在你的主要过程中

 ipcMain.on('request-token',(event)=>{

        event.reply('receive-token', token);
  })   

In your renderer在你的渲染器中

In your main renderer在你的主渲染器中

 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM