首页 > 解决方案 > 电子ipc通讯

问题描述

我正在开发一个电子应用程序,并尝试使用 ipc 通信来调用我的 index.js 文件中的一个函数,该函数包含身份验证系统。ipcMain.on("login", (event, data) => {})我需要在事件内部有这个功能。但遗憾的是该功能launch不起作用,并且我在控制台中没有任何错误。所以我假设有一种不同的方式来做到这一点。任何帮助将不胜感激

我的 index.js 文件:

const { app, BrowserWindow, ipcMain } = require('electron')


function createWindow() {
  // Create the browser window.
  var mainWindow = new BrowserWindow({
    title: "AstroLauncher",
    width: 1000,
    height: 660,
    
    webPreferences: {
      nodeIntegration: true
    }
    
  })
  mainWindow.setMenuBarVisibility(false)
  mainWindow.loadFile("home.html");
  return mainWindow;

}



app.whenReady().then(() => {
   const mainWindow = createWindow()


    app.on('activate', function () {
        if(BrowserWindow.getAllWindows.length === 0) createWindow()
    })

app.on('window-all-closed', function () {
    if(process.platform !== 'darwin') app.quit()
})

ipcMain.on("login", (event, data) => {
    

    Authenticator.getAuth(data.u, data.p).then(() => {
    event.sender.send('done')
    mainWindow.loadFile("home.html");   

    ipcMain.on('launch', () => {
      function launch() {
        alert('launched!');
      }
    })


 
}).catch((err) => {
   event.sender.send("err", { er: err })
    })
})

}).catch(err => console.log(err))

和我的 home.html 文件:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">.
    <script src="./index.js"></script>
 </head>
<body>
  <input type="button" value="Launch!" id="lanBTN" >

<script>
            const ipc = require('electron').ipcRenderer


    document.querySelector('#lanBTN').addEventListener("click", () => {
      ipc.send('launch')
    })
   
    </script>
</body>
</html>

标签: javascriptnode.jselectron

解决方案


  ipcMain.on('launch', () => {
     function launch() {
        alert('launched!');
      }
     launch() ;
 })

I think you forgot to call launch() or you can this way

  ipcMain.on('launch', () => {
        alert('launched!');
 })

推荐阅读