是否有可能在main.js文件中从web到电子调用函数?
问题描述:
所以我在main文件main.js中创建了一个函数BrowserWindow。可以说:是否有可能在main.js文件中从web到电子调用函数?
function HelloWorld(name){
return 'Hello World! said ' + name;
}
我可以在由Electron加载的html页面中调用吗?
<html>
<head>
<script type="text/javascript">
const hello = require('electron').HelloWorld
</script>
</head>
<body onLoad="alert(hello);">
</body>
</html>
我可以这样做吗?
答
是的,你可以。
在你的主进程(可能是main.js)把这个线在你的主要过程:
global.HelloWorld = function(name){
return 'Hello World! said ' + name;
}
,并在你的HTML:
<html>
<head>
<script type="text/javascript">
let {remote} = require('electron');
const hello = remote.getGlobal("HelloWorld")(); // <--() this is important
</script>
</head>
<body onLoad="alert(hello);">
</body>
</html>
但我建议使用ipcMain
和ipcRenderer
送过程之间的数据。
为什么不写一个单独的模块,然后在两个地方加载它? –
而不是返回HelloWorld。我想创建一个Socket.IO服务器。 @MikeC – Facundo
uhmm,你可以做类似的事情,使用ipcMain和ipcRenderer –