如何从电子中的 main.js 调用另一个脚本中的函数

Mar*_*ski 2 javascript system-tray node.js electron

我的电子程序中的 main.js 文件有一个小的上下文菜单,右键单击托盘图标时会打开它,如下所示:

let menuTarea = [
    {
        label: "Open window",
        click:  function(){ win.show(); }
    },
    {
        label: "**omitted**",
        click:  function(){ shell.openExternal("**omitted**"); }
    },
    {
        label: "Close completely",
        click:  function(){ app.quit(); }
    }
]
Run Code Online (Sandbox Code Playgroud)

我希望菜单按钮之一调用另一个 script.js 文件中的函数,该文件在后台运行,因为它被主窗口中的 index.html 引用。我怎样才能做到这一点?

per*_*rgy 7

您只require需要使用您想要在中使用的脚本index.html,然后通过以下main.js任一方式调用它

一个完整的例子可能是:

主文件

const { app, Menu, Tray, BrowserWindow } = require('electron')
const path = require('path')

let tray = null
let win = null
app.on('ready', () => {
  win = new BrowserWindow({
    show: false
  })
  win.loadURL(path.join(__dirname, 'index.html'))
  tray = new Tray('test.png')
  const contextMenu = Menu.buildFromTemplate([
    {label: "Open window", click: () => { win.show() }},
    {label: "Close completely", click: () => { app.quit() }},
    // call required function
    {
      label: "Call function",
      click: () => {
        const text = 'asdasdasd'
        // #1
        win.webContents.send('call-foo', text)
        // #2
        win.webContents.executeJavaScript(`
          foo('${text}')
        `)
      }
    }
  ])
  tray.setContextMenu(contextMenu)
})
Run Code Online (Sandbox Code Playgroud)

索引.html

<html>
  <body>
    <script>
      const { foo } = require('./script.js')
      const { ipcRenderer } = require('electron')
      // For #1
      ipcRenderer.on('call-foo', (event, arg) => {
        foo(arg)
      })
    </script>
  </body>
</html>
Run Code Online (Sandbox Code Playgroud)

脚本.js

module.exports = {
  foo: (text) => { console.log('foo says', text) }
}
Run Code Online (Sandbox Code Playgroud)