主进程调用渲染进程函数

1
2
3
4
5
6
7
8
无法直接调用,通信方式实现

win.webContents.send('invoke-function', 'greet', 'Hello from Main Process!');

渲染进程监听
ipcRenderer.on('invoke-function', (event, functionName, ...args) => {
console.log(`function name: ${functionName} and args: ${args}`);
});

渲染进程调用主进程函数

1
2
3
4
5
6
7
8
ipcRenderer.invoke('perform-calculation', { a: 1, b: 2 }).then(result => {
console.log(result);
});

主进程注册
ipcMain.handle('perform-calculation', async (event, { a, b }) => {
return a + b; // 返回简单的加法结果
});

页面调用渲染进程函数

1
2
3
4
5
6
7
8
window.electronAPI.performCalculation(1, 2).then(result => {
console.log(result);
});

渲染进程暴漏
contextBridge.exposeInMainWorld('electronAPI', {
performCalculation: (a, b) => ipcRenderer.invoke('perform-calculation', { a, b })
});

渲染进程发送数据给页面

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// 暴露 API 给页面
contextBridge.exposeInMainWorld('api', {
selectFile: () => ipcRenderer.invoke('select-file'),
on: (channel, callback) => {
const validChannels = ['image-processed', 'send-progress'];
if (validChannels.includes(channel)) {
ipcRenderer.on(channel, callback); // 监听主进程的事件
}
},
onUploadStatus: (callback) => ipcRenderer.on('upload-status', (_, data) => callback(_,data)),
});

页面实时监听
window.electronAPI.on('send-progress', (event, message) => {
console.log(message);
});

主进程给渲染进程发送数据

1
2
3
4
5
6
7
渲染进程监听
ipcRenderer.on('message', (event, message) => {
console.log(message);
});

主进程发送
win.webContents.send('message', message);

渲染进程调用页面函数

1
webContents.executeJavaScript('myFunction()');

补充一个主进程发送数据给页面的方法,很强

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
主进程
win.webContents.send('call-page-function', 'showMessage', 'Hello from Main Process!');

渲染进程在页面发起调用的时候进行监听
contextBridge.exposeInMainWorld('electronAPI', {
onFunctionCall: (callback) => ipcRenderer.on('call-page-function', (event, functionName, ...args) => {
callback(functionName, ...args);
}),
});

页面
// 页面定义的函数集合
const pageFunctions = {
showMessage: (message) => {
console.log('Executing showMessage:', message);
document.getElementById('output').innerHTML += `<p>${message}</p>`;
},
logData: (data) => {
console.log('Logging data:', data);
},
};
// 监听主进程的函数调用
window.electronAPI.onFunctionCall((functionName, ...args) => {
if (pageFunctions[functionName]) {
pageFunctions[functionName](...args); // 调用指定函数
} else {
console.error(`Function "${functionName}" not found.`);
}
});