I'm getting an error in which electronjs is not able to load preload script. I'm making a tool in which i can upload a text file and it will return me the content from the file.
I have file input with id 'upload' in my index.html.
Main.js
const { app, BrowserWindow, dialog, ipcMain } = require("electron");
const path = require("path");
function createWindow() {
const win = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
preload: path.join(__dirname, "preload.js"),
},
});
win.webContents.openDevTools();
win.loadFile("index.html");
}
ipcMain.on("file-request", (event) => {
if (process.platform !== "darwin") {
dialog
.showOpenDialog({
title: "Select the File to be uploaded",
defaultPath: path.join(__dirname, "../assets/"),
buttonLabel: "Upload",
filters: [
{
name: "Text Files",
extensions: ["txt", "docx"],
},
],
properties: ["openFile"],
})
.then((file) => {
console.log(file.canceled);
if (!file.canceled) {
const filepath = file.filePaths[0].toString();
console.log(filepath);
event.reply("file", filepath);
}
})
.catch((err) => {
console.log(err);
});
}
});
preload.js
const { ipcRenderer } = require("electron");
const uploadFile = document.getElementById("upload");
uploadFile.addEventListener("click", () => {
ipcRenderer.send("file-request");
});
ipcRenderer.on("file", (event, file) => {
console.log("Obtained File from main process: " + file);
});
I have fixed the issue by doing document selector thing in renderer.js and making exposeInMainWorld in preload.js