You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Electron应用的index.html中调用main.js内的函数

在Electron中从渲染进程(index.html)调用主进程(main.js)函数的方法

Electron里主进程(main.js)和渲染进程(index.html所在进程)是相互隔离的,不能直接跨进程调用函数,必须通过**IPC(进程间通信)**来实现,下面是具体的实现步骤:

1. 主进程(main.js)配置IPC监听

在main.js中,通过ipcMain模块监听渲染进程的调用请求,执行目标函数后可返回结果:

const { app, BrowserWindow, ipcMain } = require('electron');
const path = require('path');

// 你需要被调用的主进程函数
function handleMainTask(inputArg) {
  return `主进程已处理参数:${inputArg}`;
}

let mainWindow;

function createWindow() {
  mainWindow = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      // 生产环境建议开启上下文隔离,通过preload脚本暴露接口,下文会补充
      contextIsolation: true,
      preload: path.join(__dirname, 'preload.js')
    }
  });

  mainWindow.loadFile('index.html');
}

// 监听渲染进程的调用请求,支持异步返回结果
ipcMain.handle('invoke-main-function', async (event, arg) => {
  return handleMainTask(arg);
});

app.whenReady().then(createWindow);

2. 编写Preload脚本(生产环境必备)

为了保证安全性,开启contextIsolation后,需要通过preload脚本向渲染进程暴露合法的IPC接口:

// preload.js
const { contextBridge, ipcRenderer } = require('electron');

// 向渲染进程暴露可控的API
contextBridge.exposeInMainWorld('electronAPI', {
  callMainFunction: (arg) => ipcRenderer.invoke('invoke-main-function', arg)
});

3. 渲染进程(index.html)发起调用

在index.html的脚本中,通过preload暴露的接口发起对主进程函数的调用:

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>IPC调用演示</title>
</head>
<body>
  <button onclick="triggerMainFunction()">调用主进程函数</button>
  <p id="response"></p>

  <script>
    async function triggerMainFunction() {
      const result = await window.electronAPI.callMainFunction('测试输入');
      document.getElementById('response').textContent = result;
    }
  </script>
</body>
</html>

关键注意事项

  • 主进程与渲染进程的隔离是Electron的核心安全机制,禁止尝试直接跨进程引用函数或变量。
  • 如果不需要返回结果,可使用ipcRenderer.send()搭配ipcMain.on()实现单向通信。
  • 开发环境若想快速测试,可临时关闭contextIsolation并开启nodeIntegration,但生产环境必须恢复安全配置。

内容的提问来源于stack exchange,提问作者Felixmax_

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 23:30:49