是否可以从网络到电子调用main.js文件中的函数?

Fac*_*ndo 3 javascript node.js electron

所以我在主文件main.js中有一个函数,可以创建Electron BrowserWindow。可以说:

function HelloWorld(name){
    return 'Hello World! said ' + name;
}
Run Code Online (Sandbox Code Playgroud)

我可以在Electron加载的html页面中调用吗?

<html>
    <head>
        <script type="text/javascript">
            const hello = require('electron').HelloWorld
        </script>
    </head>
    <body onLoad="alert(hello);">
    </body>
</html>
Run Code Online (Sandbox Code Playgroud)

我可以那样做吗?

Max*_*meF 5

是的你可以。

在您的主要流程(可能是main.js)中,将以下行放入您的主要流程:

global.HelloWorld = function(name){
    return 'Hello World! said ' + name;
}
Run Code Online (Sandbox Code Playgroud)

并在您的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>
Run Code Online (Sandbox Code Playgroud)

但是我建议在进程之间使用ipcMainipcRenderer发送数据。

  • 它的说法 rquire 未在 index.html 中定义 (2认同)