# 2.6.使用IPC进行通讯

index.html

```markup
<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title>Hello World!</title>
  </head>
  <body>
    <h1>Hello World!</h1>
    We are using Node.js <span id="node-version"></span>
    <button id="send">Send to main</button>
    <span id="message"></span>

    <script src="./renderer.js"></script>
  </body>
</html>
```

renderer.js

```javascript
const {ipcRenderer} = require('electron') // 引入ipcRenderer

window.addEventListener('DOMContentLoaded',()=>{
    document.getElementById('node-version').innerHTML = process.versions.node
    document.getElementById('send').addEventListener('click',()=>{
        ipcRenderer.send('message','hello form renderer') // 发送事件
    })
    ipcRenderer.on('reply',(event,arg) =>{                // 接收事件
        document.getElementById('message').innerHTML = arg
        console.log(arg)
    })
})
```

main.js

```javascript
const { app, BrowserWindow, ipcMain } = require('electron') // 引入ipcMain

app.on('ready',()=>{
  let mainWindow = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      nodeIntegration: true
    }
  })
  mainWindow.loadFile('index.html')
  mainWindow.webContents.openDevTools()
  ipcMain.on('message',(event,arg) =>{                     // 接收Renderer进程发来的事件
    console.log(event)
    console.log(arg)
    event.reply('reply', 'hello from main process')     // 回复事件
  })
})
```
