gpt4 book ai didi

javascript - 如何在 react 中导入ipcRenderer?

转载 作者:行者123 更新时间:2023-11-29 20:58:13 24 4
gpt4 key购买 nike

我尝试在 React 应用中导入 ipcRenderer

import {ipcRenderer} from 'electron';

但是我得到这个错误信息:require is not defined

最佳答案

您需要按照我在 this comment 中概述的步骤进行操作.这些步骤确保您的 Electron 应用程序的安全性。

ma​​in.js

const {
app,
BrowserWindow,
ipcMain
} = require("electron");
const path = require("path");
const fs = require("fs");

// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the JavaScript object is garbage collected.
let win;

async function createWindow() {

// Create the browser window.
win = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
nodeIntegration: false, // is default value after Electron v5
contextIsolation: true, // protect against prototype pollution
enableRemoteModule: false, // turn off remote
preload: path.join(__dirname, "preload.js") // use a preload script
}
});

// Load app
win.loadFile(path.join(__dirname, "dist/index.html"));

// rest of code..
}

app.on("ready", createWindow);

ipcMain.on("toMain", (event, args) => {
fs.readFile("path/to/file", (error, data) => {
// Do something with file contents

// Send result back to renderer process
win.webContents.send("fromMain", responseObj);
});
});

preload.js

const {
contextBridge,
ipcRenderer
} = require("electron");

// Expose protected methods that allow the renderer process to use
// the ipcRenderer without exposing the entire object
contextBridge.exposeInMainWorld(
"api", {
send: (channel, data) => {
// whitelist channels
let validChannels = ["toMain"];
if (validChannels.includes(channel)) {
ipcRenderer.send(channel, data);
}
},
receive: (channel, func) => {
let validChannels = ["fromMain"];
if (validChannels.includes(channel)) {
// Deliberately strip event as it includes `sender`
ipcRenderer.on(channel, (event, ...args) => fn(...args));
}
}
}
);

index.html

<!doctype html>
<html lang="en-US">
<head>
<meta charset="utf-8"/>
<title>Title</title>
</head>
<body>
<script>
window.api.receive("fromMain", (data) => {
console.log(`Received ${data} from main process`);
});
window.api.send("toMain", "some data");
</script>
</body>
</html>

关于javascript - 如何在 react 中导入ipcRenderer?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48148021/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com