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

How to call a function in another script from main.js in electron

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

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

我希望其中一个菜单按钮调用另一个 script.js 文件中的函数,该文件在后台 运行,因为它被 index.html主要window。我该怎么做?

您只需 require 您想要在 index.html 中使用的脚本,然后通过

main.js 调用它

一个完整的例子可以是:

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)
})

index.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>

script.js

module.exports = {
  foo: (text) => { console.log('foo says', text) }
}