I clone electron-quick-start demo, and test ipcMain function. Follow the document add this in main.js
const { ipcMain } = require('electron')
ipcMain.on('asynchronous-message', (event, arg) => {
console.log(arg) // print "ping"
event.reply('asynchronous-reply', 'pong')
})
ipcMain.on('synchronous-message', (event, arg) => {
console.log(arg) // print "ping"
event.returnValue = 'pong'
})
in preload.js
const { ipcRenderer } = require('electron')
console.log(ipcRenderer.sendSync('synchronous-message', 'ping')) // print "pong"
ipcRenderer.on('asynchronous-reply', (event, arg) => {
console.log(arg) // print "pong"
})
ipcRenderer.send('asynchronous-message', 'ping')
I can't add in renderer.js because it said
// This file is required by the index.html file and will
// be executed in the renderer process for that window.
// No Node.js APIs are available in this process because
// `nodeIntegration` is turned off. Use `preload.js` to
// selectively enable features needed in the rendering
// process.
and it can't find require(in renderer.js)
The problem is the development tool can't get value in preload.js at this one
ipcRenderer.on('asynchronous-reply', (event, arg) => {
console.log(arg) // print "pong"
})
ipcRenderer.send('asynchronous-message', 'ping')
my node.js terminal can get the 'ping' string, and this is development tool's issues==> screenshot
The index.html file of electron-quick-start demo contains the CSP rules:
<meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self'">
<meta http-equiv="X-Content-Security-Policy" content="default-src 'self'; script-src 'self'">
change it to:
<meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self' 'unsafe-eval'">
<meta http-equiv="X-Content-Security-Policy" content="default-src 'self'; script-src 'self' 'unsafe-eval'">
because eval-expressions are used somewhere. Yes, it is "not secure", but this is just demo. Later you can sort out what of "eval" construct is used and fix those.
Also you can remove both above meta tags to avoid troubles with Content Security Policy at first steps.