'Unable to read API key from rendered process which is defined in preload.js for inter-process communication in electronJS
I'm getting an undefined object error for the api key (setScripts) in rendered process (i.e. install.js). I'm trying to capture data in rendered process and send it to main process (i.e. main.js) with the help of preload.js.
the error-> Uncaught TypeError: Cannot read properties of undefined (reading 'setScripts') at HTMLButtonElement. (install.js:10:38)
-> install.js
const btn = document.querySelector('#BtnInstall');
btn.addEventListener('click', (event) => {
const checkboxes = document.querySelectorAll('input[name="installOption"]:checked');
const values = [];
checkboxes.forEach((checkbox) => {
values.push(checkbox.value);
});
window.installScriptsAPI.setScripts(values);
for (const checkbox of document.querySelectorAll('.checkbox1')) {
checkbox.checked = false //for unselection
}
});
->preload.js
const{ contextBridge, ipcRendrer} = require('electron');
contextBridge.exposeInMainWorld('installScriptsAPI',{
setScripts: (values) => ipcRendrer.send('install-scripts',values)
})
->main.js
console.log('main process working');
const { app, BrowserWindow, ipcMain } = require('electron')
const path = require('path')
function createWindow(){
const win = new BrowserWindow({ webPreferences :{
nodeIntegration:true,
contextIsolation:false,
preload: path.join(__dirname,'preload.js')
}, width: 1000, height: 600 })
win.loadFile('index.html');
win.webContents.openDevTools();
}
function catchInstallScripts(event,values){
console.log(values);
}
app.whenReady().then(() => {
createWindow();
ipcMain.on('install-scripts',catchInstallScripts);
});
app.commandLine.appendSwitch('disable-gpu-sandbox');
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
