After creating an electron application with
npm install create-electron-app -g
create-electron-app "Electron App"
an event listener was added to index.html by placing this script tag at the end of the body.
<script>
const electron = require("electron");
const ipcRenderer = electron.ipcRenderer;
ipcRenderer.on('cpu', (event,data) => {// This isn't picking up the sent data.
console.log('data is: ' + data);
});
</script>
With the following js to start the app
const { app, BrowserWindow } = require('electron');
const path = require('path');
const os = require('os-utils');
// irrelevant code left out
const createWindow = () => {
const mainWindow = new BrowserWindow({
width: 1000,
height: 600,
webPreferences: {
nodeIntegration: true,
contextIsolation: false
}
});
mainWindow.loadFile(path.join(__dirname, 'index.html'));
mainWindow.webContents.openDevTools();
os.cpuUsage(function(v){
console.log(v*100);
mainWindow.webContents.send('cpu', v*100);// this should send this information to the webpage's ipcRenderer.
});
};
app.on('ready', createWindow);
Nothing happens after I start the app. The dev console opens up but no data is logged to the console from this line: console.log('data is: ' + data);
I've tried wrapping the os.cpuUsage(…) a listener that waits for the entire page to load, as was suggested in this answer
mainWindow.webContents.on('did-finish-load', ()=>{
os.cpuUsage(function(v){
console.log(v*100);
mainWindow.webContents.send('cpu', v*100);// this should send this information to the webpage's ipcRenderer.
})
});
I have also checked to see if .on is actually creating an event listener by adding
console.log(ipcRenderer.listenerCount())
to the end of the script tag. It logged '0'
I have also tried changing ipcRenderer.on to ipcRenderer.once with no change in behavior.
Additionally, I added these console.log lines after the const declarations in the <script> tag:
console.log('test')
console.log(electron)
console.log(ipcRenderer)
These were successfully logged.