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

Electron开发:如何将.js文件中的变量传递至.html页面?

解决方案:Electron中主进程向渲染进程传递文件列表并循环展示

刚接触Electron确实会遇到进程间通信的问题,别担心,咱们一步步来解决——核心思路是利用Electron的进程间通信(IPC)机制,把主进程里的文件列表传递到渲染进程,再在HTML页面里用循环渲染出来。

1. 主进程获取文件列表并发送消息

假设你的文件夹遍历逻辑写在主进程的main.js里,先完成文件遍历,再通过IPC把projectFile数组发送给渲染进程:

// main.js
const { app, BrowserWindow, ipcMain } = require('electron');
const fs = require('fs');
const path = require('path');

function createWindow() {
  const mainWindow = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      // 配置预加载脚本,这是Electron推荐的安全通信方式
      preload: path.join(__dirname, 'preload.js')
    }
  });

  mainWindow.loadFile('index.html');

  // 你的文件夹遍历函数
  function getProjectFiles(targetFolder) {
    const projectFiles = [];
    function traverseDir(dir) {
      const files = fs.readdirSync(dir);
      for (const file of files) {
        const fullPath = path.join(dir, file);
        const stats = fs.statSync(fullPath);
        if (stats.isFile()) {
          projectFiles.push(fullPath); // 把文件路径存入数组
        } else if (stats.isDirectory()) {
          traverseDir(fullPath); // 递归遍历子文件夹
        }
      }
    }
    traverseDir(targetFolder);
    return projectFiles;
  }

  // 示例:遍历当前项目根目录
  const projectFiles = getProjectFiles(__dirname);

  // 等页面加载完成后,发送文件列表给渲染进程
  mainWindow.webContents.on('did-finish-load', () => {
    mainWindow.webContents.send('send-project-files', projectFiles);
  });
}

app.whenReady().then(createWindow);

2. 配置预加载脚本(安全暴露通信API)

Electron现在要求用contextBridge来安全地在主进程和渲染进程间传递API,咱们在preload.js里配置一下:

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

// 给渲染进程暴露一个安全的监听函数
contextBridge.exposeInMainWorld('electronAPI', {
  onReceiveFiles: (callback) => {
    ipcRenderer.on('send-project-files', (event, files) => callback(files));
  }
});

3. HTML页面接收列表并循环渲染

现在在你的index.html里,通过预加载的API接收文件列表,用forEach循环把每个文件渲染到页面上:

<!-- index.html -->
<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>项目文件列表</title>
  <style>
    .file-item {
      margin: 8px 0;
      padding: 6px;
      border-bottom: 1px solid #eee;
      font-family: monospace;
    }
  </style>
</head>
<body>
  <h1>项目文件列表</h1>
  <div id="file-container"></div>

  <script>
    // 监听主进程发来的文件列表
    window.electronAPI.onReceiveFiles((projectFiles) => {
      const container = document.getElementById('file-container');
      
      // 循环遍历文件数组,生成DOM元素添加到页面
      projectFiles.forEach((filePath) => {
        const fileItem = document.createElement('div');
        fileItem.className = 'file-item';
        fileItem.textContent = filePath;
        container.appendChild(fileItem);
      });
    });
  </script>
</body>
</html>

额外提示:如果遍历逻辑在渲染进程(不推荐生产用)

要是你暂时不想折腾主进程,只是开发测试用,可以在渲染进程里直接遍历,但这样需要开启nodeIntegration(有安全风险,生产环境别用):

在main.js的BrowserWindow配置里加:

webPreferences: {
  nodeIntegration: true,
  contextIsolation: false
}

然后在HTML的script里直接写遍历和循环:

<script>
  const fs = require('fs');
  const path = require('path');

  function getProjectFiles(targetFolder) {
    // 和之前一样的遍历逻辑
  }

  const projectFiles = getProjectFiles('./');
  const container = document.getElementById('file-container');
  projectFiles.forEach(file => {
    const item = document.createElement('div');
    item.className = 'file-item';
    item.textContent = file;
    container.appendChild(item);
  });
</script>

不过还是强烈推荐第一种主进程+预加载脚本的方式,符合Electron的安全最佳实践。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 08:50:52