【问题标题】:Is it possible to call a function in main.js file from web to electron?是否可以将 main.js 文件中的函数从 web 调用到电子?
【发布时间】:2016-09-14 20:41:27
【问题描述】:

所以我在主文件 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>

我可以这样做吗?

【问题讨论】:

  • 为什么不写一个单独的模块然后在两个地方加载呢?
  • 而不是返回 HelloWorld。我只想创建一个 Socket.IO 服务器。 @MikeC
  • 嗯,你可以做类似的事情,使用 ipcMain 和 ipcRenderer

标签: javascript node.js electron


【解决方案1】:

是的,你可以。

在您的主进程(可能是 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 在进程之间发送数据。

【讨论】:

  • 它的说法 rquire 没有在 index.html 中定义
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-08-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-09-06
相关资源
最近更新 更多