如何通过Preload.js接收接口数据并更新Home.html页面UI?
实现实时更新UI的方案
要在接收到test_runner_steps后实时更新home.html的UI,核心是通过Electron的IPC(进程间通信)机制,将预加载脚本中获取到的数据传递到渲染进程,再由渲染进程更新页面元素。
1. 修改preload.js,添加IPC通信逻辑
首先需要确保能解析POST请求的JSON体,同时通过IPC把数据发送给渲染进程,并暴露监听接口给页面:
const { contextBridge, ipcRenderer } = require('electron'); const express = require('express'); const bodyParser = require('body-parser'); const expressApp = express(); expressApp.use(bodyParser.json()); let expressListen; contextBridge.exposeInMainWorld('electronAPI', { startServer: () => { expressListen = expressApp.listen(3009, () => { console.log('Server started on port 3009'); }); expressApp.post('/run', (req, res) => { const { test_runner_steps } = req.body; // 发送数据到渲染进程 ipcRenderer.send('test-steps-updated', test_runner_steps); res.send('Hello World!'); }); }, // 给渲染进程提供监听数据更新的方法 onTestStepsUpdate: (callback) => { ipcRenderer.on('test-steps-updated', (_, steps) => callback(steps)); } });
2. 在home.html中监听数据并更新UI
在页面中调用预加载暴露的接口,启动服务器并监听数据变化,一旦收到新数据就刷新页面内容:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Home Page</title> </head> <body> <div id="testStepsContainer"></div> <script> // 启动Express服务器 window.electronAPI.startServer(); // 监听测试步骤更新事件 window.electronAPI.onTestStepsUpdate((steps) => { const container = document.getElementById('testStepsContainer'); container.innerHTML = ''; // 根据steps生成对应的UI元素,可自定义展示格式 steps.forEach((step, idx) => { const stepEl = document.createElement('div'); stepEl.className = 'test-step'; stepEl.textContent = `步骤 ${idx + 1}: ${JSON.stringify(step)}`; container.appendChild(stepEl); }); }); </script> </body> </html>
必要的依赖安装
执行以下命令安装body-parser,用于解析POST请求的JSON体:
npm install body-parser
补充说明
如果你的Express服务器实际运行在Electron主进程(而非preload脚本),只需把服务器逻辑移到主进程,然后用ipcMain监听主进程内的事件,再通过webContents.send把数据发送到渲染进程,原理一致。
内容的提问来源于stack exchange,提问作者Faizan Ahmed
相关产品推荐
相关产品推荐

