[英]Electron.js how to invoke a function in preload.js and use in main.js
[英]Getting an error while executing 'preload.js' in electron.js
我收到一個錯誤,其中 electronjs 無法加載預加載腳本。 我正在制作一個工具,我可以在其中上傳文本文件,它將返回文件中的內容。
我的 index.html 中有 ID 為“上傳”的文件輸入。
主.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);
});
我已經通過在renderer.js
中執行文檔選擇器並在preload.js
中創建exposeInMainWorld
解決了這個問題
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.