I am a beginner coder and not that good so pls dont mind my code, i am trying to make an application in electron js that opensan img file and displays it in the app. and i am having to send a message from the main process so i am using webContents.send but, i am having an error which says that
(node:11908) UnhandledPromiseRejectionWarning: TypeError: Cannot read properties of undefined (reading 'webContents')
can someone help me pls
main.js (main process):
const {app, BrowserWindow, ipcMain, dialog, globalShortcut, ipcRenderer, mainWindow, webContents}=require('electron')
const path=require('path')
const fs = require('fs')
function creatWindow(){
const title='hello'
const content='hi hello'
const win= new BrowserWindow({
height:768,
width:1366,
title:"Ahmad's Website",
webPreferences:{
preload: path.join(__dirname,'preload.js')},
nodeIntegration: true,
webviewTag: true
});
win.loadFile('src/index.html')
win.maximize()
ipcMain.on('upload', (event)=>{
dialog.showOpenDialog().then((result)=>{
c=String(result.filePaths)
f=c.replace('['/']','')
console.log(f)
mainWindow.webContents.send('uploadfile',f)
})
})
};
app.whenReady().then(creatWindow);
preload.js (preload script)
const {contextBridge, ipcRenderer}= require('electron');
window.addEventListener('DOMContentLoaded',()=>{
const upload_fl=document.getElementById('upload')
upload_fl.addEventListener('click', ()=>{
ipcRenderer.send('upload')
ipcRenderer.on('uploadfile', (event,value)=>{
const path1=value
document.getElementById('img').src=path1
})
})
})
index.html (index page of app)
<!DOCTYPE html>
<html>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial scale=1">
<head>
<style>
</style>
<script src="script.js"></script>
<title>my app</title>
</head>
<body>
<h1 id="h1c">HELLO I AM AHMAD</h1> first input is name of file. and second input is content
<button id="upload">Upload</button>
<br><br>
<img id="img" src="" alt="">
</body>
</html>
I spend like 2 or 3 days trying to look for answers. there was another question on stackoverflow but that was a different situation as i tried the solution and it didn’t work
codegame123 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.