![](/img/trans.png)
[英]Is it possible to call a function in main.js file from web to electron?
[英]How to call a function in another script from main.js in 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
require
要使用的腳本,然后通過以下方式從main.js
調用該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) }
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.