簡體   English   中英

Electron - 將參數從 main.js 傳遞到 html

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM