是否可以从网络到电子调用 main.js 文件中的函数?
Is it possible to call a function in main.js file from web to electron?
所以我在主文件 main.js 中有一个函数可以创建 Electron BrowserWindow。让我们说:
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
在进程之间发送数据。
所以我在主文件 main.js 中有一个函数可以创建 Electron BrowserWindow。让我们说:
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
在进程之间发送数据。