如何调用函数是电子网页中的renderer.js / main.js [英] How to call a function is renderer.js/main.js from web page in electron
问题描述
在这里成为电子新手,我已经用React JS构建了一个简单的Web应用程序,并能够通过调用
Newbie to electron here, I have built a simple web application with React JS and able to view it in a window by calling
window.loadFile('./build/index.html');
现在我想调用位于renderer.js / main.js中的函数,该函数应读取文件系统并将数据返回到Web应用程序。
Now i would want to call a function located in say renderer.js/main.js which should read file system and return data to the web application.
我已经在renderer.js中尝试过此操作
I have already tried this in renderer.js
const { ipcRenderer } = require('electron');
document.getElementById('#button').addEventListener('click', function (event) {
//read file contents
console.log('file contents');
});
但是这里有2个问题
- 控件来自renderer.js,相反,我希望
控件位于React的网页上。 - 读取的内容应返回到网页,以便可以在网页中显示。
推荐答案
您应该能够直接在React组件脚本上导入/请求ipcRenderer,并且可以将文件加载到生命周期挂钩上。 renderer.js只是在(电子)网页上执行客户端javascript的一种方法,但其他方法也可以解决问题。
You should be able to import/require ipcRenderer directly on your react component scripts and maybe load the file on a lifecycle hook. The 'renderer.js' is just one way to execute client side javascript on the (electron-)web page but any other way also does the trick.
如果可以的话不会从Web应用程序导入或要求电子(我还没有玩过电子反应样板),那么您可以编写一个所谓的预加载脚本,在创建浏览器窗口时加载该脚本(请参阅该文档)并放入像这样的窗口上的ipcRenderer:
If you can't import or require electron from the webapp (I didn't play with the electron-react-boilerplate yet), then you could write a so called preload script, load that when you create the browser window (see that documentation) and put the ipcRenderer on window like so:
const {ipcRenderer} = require('electron')
window.ipcRenderer = ipcRenderer
然后您可以从react应用访问它。
Then you can access it from the react app.
这篇关于如何调用函数是电子网页中的renderer.js / main.js的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!