我正在为我的项目测试 ipcRenderer 进程,并且在我的 javascript 文件中我需要 ipc Renderer
const {ipcRenderer} = require('electron')
在我的html文件中,我已经声明了
<script type="javascript" src="myjavascriptfile.js"></script>
一旦我这样做,我的 js 文件中声明的任何代码、函数或任何内容都将无法工作,控制台中不会出现任何错误或任何其他通知。
我对电子有点陌生,如果我的问题听起来很愚蠢,我很抱歉。我已经在我的 main.js (电子的主文件)中设置了 nodeIntegration:true 和 contextIsolation:false 。 但是,如果问题有任何其他解决方案,我的目的是 - 获取文本区域值和行 id,将其发送到对象,并将其保存为 json 文件。我使用 ipcRenderer 将值发送到 ipcMain,然后使用节点中的 fs 来创建文件。然而,如上所述,我无法让它工作。
这只是我想要如何使用的示例,当然这不是最终的代码,但如果我让它工作,我将处理其他东西:
const ipcRenderer = require('electron').remote
const Savebtn = document.getElementById("SaveSong")
let song = ['text', 'id']
Savebtn.addEventListener("click",()=>{
ipcRenderer.send('save', song)
console.log(song)
})
首先,禁用
nodeIntegration
和/或启用 contextIsolation
将会在您的应用程序中创建 安全漏洞。除非您有充分的理由并且您确信自己在做什么,否则不要这样做。接下来,remote
模块自Electron 12起已被弃用,并自Electron 14起被删除,您不应该(也不需要)使用它。
当所有内容都配置为安全时,您需要使用preload文件才能使用IPC。例如:
预加载
const { contextBridge, ipcRenderer } = require("electron");
contextBridge.exposeInMainWorld("electronAPI", {
saveSong: (song) => ipcRenderer.send("save", song)
});
渲染器
Savebtn.addEventListener("click", () => {
window.electronAPI.saveSong(song);
});
确保您没有在
渲染器进程中使用
require
,并且仅将沙箱可用的内容导入到预加载中(否则您会收到更多错误)。您可以在文档中阅读有关安全性的更多信息,并在文档中找到更多工作示例。