在electron中,渲染进程与主进程交互时,引入ipcRenderer报错
Uncaught ReferenceError: require is not defined
渲染进程是这么写的:
<!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>,
Chromium <span id="chrome-version"></span>,
and Electron <span id="electron-version"></span>.
<!-- You can also require other files to run in this process -->
<!-- <script src="./renderer.js"></script> -->
<script>
const ipcMain = require('electron').ipcMain
ipcRenderer.send('zhujinchengshou','我是渲染进程的')
</script>
</body>
</html>
修改成下面,会得到这个错误:Uncaught SyntaxError: Unexpected token {
import {ipcRenderer} from 'electron'
解决问题就直接这么写:
<script>
const ipcRenderer = require('electron').ipcRenderer;
ipcRenderer.send('zhujinchengshou','我是渲染进程的')
</script>
然后需要在main.js也就是主进程中写上集成node的那个工具为true
mainWindow = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
nodeIntegration: true, // 是否集成 Nodejs,把之前预加载的js去了,发现也可以运行
}
})
就不会出现这个问题了