问题描述
在一个 Electron-React-Typescript 应用程序中,我设法在预加载中通过 contextBridge.exposeInMainWorld 将消息从渲染器进程发送到主进程,但是在返回的路上,来自主进程的处理后的输出实际上通过并到达了 preload.ts,但它没有达到渲染器进程。 它一定是真正“愚蠢”的东西,但我不知道什么是“罪魁祸首”。所以,我请求你的帮助。
预加载.ts:
const {
contextBridge,ipcRenderer
} = require("electron")
contextBridge.exposeInMainWorld(
"api",{
send: (channel,data) => {
ipcRenderer.invoke(channel,data).catch(e => console.log(e))
},receive: (channel,func) => {
ipcRenderer.on(channel,(event,...args) => func(...args))
//ipcRenderer.on(channel,...args) => {
//console.log("ipcRenderer.on-args: ",args);
//});
}
)
index.d.ts :
declare interface Window {
api: {
send: (channel: string,...arg: any) => void;
receive: (channel: string,func: (event: any,...arg: any) => void) => void;
}
}
main.ts :
ipcMain.handle("path-to-url",(IpcMainEvent,path) => {
console.log("received a request from viewerDemo");
if (mainWindow) {
let urlified = url.pathToFileURL(path);
console.log("urlified = url.pathToFileURL(path) : ",urlified);
console.log("urlified.href= ",urlified.href);
console.log("urlified.pathname= ",url.pathToFileURL(path).pathname);
mainWindow.webContents.on("dom-ready",() => {
mainWindow.webContents.send("path-to-url","ohhhhhhhhhhhhhhhh");
mainWindow.webContents.send("path-to-url",url.pathToFileURL(path).pathname);
});
}
});
渲染器进程(数据显示不正确!):
viewerDemo.tsx
import * as React from 'react';
import Viewer from 'react-viewer';
let path_1 = './images/natural-scene.jpeg';
let url_path;
const pathToUrlFunc = (path): string => {
console.log("pathToUrlFunc called");
window.api.send("path-to-url",path);
let urlPath;
window.api.receive("path-to-url",args) => {
console.log("window.api.receive called!");
console.log("window.api.receive-args[0]: ",args[0]);
urlPath = args[0];
});
return urlPath;
}
function ViewerDemo() {
const [ visible,setVisible ] = React.useState(false);
let urlpath = pathToUrlFunc(path_1);
console.log("urlpath: ",urlpath);
return (
<div>
<button onClick={() => { setVisible(true); } }>show</button>
<Viewer
visible={visible}
onClose={() => { setVisible(false); } }
images={[{src: 'https://www.fotolip.com/wp-content/uploads/2016/05/Nature-Scenes-
21.jpg',alt: ''}]}
//images={[{src: urlpath,alt: ''}]}
/>
</div>
);
}
export default ViewerDemo;
在主要我得到:path received from main: ./images/natural-scene.jpeg
而从主返回渲染器的路上我得到:Cannot read property '0' of undefined
如果在我放置的 api 的“接收”部分的 contextBridge.exposeInMainWorld 中:
receive: (channel,func) => {
//ipcRenderer.on(channel,...args) => func(...args))
ipcRenderer.on(channel,...args) => {
console.log("ipcRenderer.on-args: ",args);
});
}
我不再收到那个错误,在 preload.ts 中出现了来自 main.ts 的正确消息,但渲染器进程仍然没有得到它:
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)