electron窗口和主进程通信ipc

前端和后台通信ipc

主进程

const electron = require('electron')
 
const { app } = electron
 
const ipc = require('electron').ipcMain
 
const { BrowserWindow } = electron
 
let win
 
ipc.on('getMsg', (sys, msg) => {
  console.log(msg)  //接收窗口传来的消息
})
 
app.on('ready', createWindow)
 
app.on('window-all-cloased', () => {
  if (process.platform !== 'drawin') {
    app.quit()
  }
})
 
app.on('activate', () => {
  if (win === null) {
    createWindow()
  }
})
 
function createWindow() {
  win = new BrowserWindow({
    width: 600,
    height: 400
  })
 
  win.loadURL(`file://${__dirname}/app/index.html`)
 
  // win.webContents.openDevTools() //开启调试工具
 
  win.on('close', () => {
    win = null
  })
  win.on('resize', () => {
    win.reload()
  })
 
  win.on('closed', () => {
    win = null
  })
}

index.html

<!DOCTYPE html>
<html lang="en">
 
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>myapp</title>
</head>
 
<body>
  <h1>electron-app-3</h1>
  <input type="" name="" id="ipt" value="">
  <button type="button" onclick="connectMain()">和主进程通信</button>
 
 
  <script>
    const ipc = require('electron').ipcRenderer;
    var ipt = document.getElementById('ipt')
 
    function connectMain() {
      console.log('index.html', ipt.value);
      ipc.send('getMsg', ipt.value)
    }
  </script>
</body>
 
</html>

猜你喜欢

转载自blog.csdn.net/weixin_42762089/article/details/87912222
今日推荐