电子程序中的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引用的。我该怎么办?
答案 0 :(得分:1)
您只需要require
要在index.html
中使用的脚本,然后通过{p>
完整的示例可能是:
main.js
main.js
index.html
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)
})
script.js
<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>