javascript - 如何从 Electron 中的main.js调用另一个脚本中的函数

标签 javascript node.js electron system-tray

我的 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(); }
    }
]

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

最佳答案

您只需 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) }
}

关于javascript - 如何从 Electron 中的main.js调用另一个脚本中的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52636427/

相关文章:

javascript - 从所有列表项更新 CSS 类属性的纯 javascript 方法?

javascript - Bootstrap - 在模态后面编辑 TextArea

node.js - 请求 X509 证书

javascript - Electron 桌面应用程序文件结构

node.js - 启动应用程序上的 Electron 闪屏

javascript - 选择复选框的背景颜色

javascript - 当标记超出给定区域时如何收到警报

node.js - 无法在 Node 中使用表单数据插入数据

javascript - d3.js 安装故障排除 'Let' s 制作 map ' 教程

javascript - 使用 Javascript 从本地文件夹读取 CSV 文件