我的 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
调用它:
-
executeJavaScript
在页面上 - 或使用
ipc
communication
一个完整的例子可以是:
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/