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

如何在Electron的HTML文件中调用主进程获取的用户名?

解决Electron中从HTML访问主进程用户名的问题

嘿,我来帮你搞定这个在Electron里把主进程的用户名传递到HTML页面的问题!你之前尝试的思路有可取之处,但有些细节没处理对,尤其是Electron的安全配置和版本差异的问题,我给你梳理两种靠谱的方案:

方案1:修复你当前用的「全局变量+remote」方式

你的思路本身没问题,但Electron 14及以后的版本默认禁用了remote模块,而且渲染进程默认也不让直接用Node.js的require,这就是你之前遇到「require未定义」的原因,根本不用browserify,调整主进程的配置就行:

第一步:修改main.js的配置

const { app, BrowserWindow } = require('electron');
const username = require('username');
const path = require('path'); // 记得引入path模块

// 获取用户名
var uName = username.sync();

// 针对Electron 14+启用remote模块
require('@electron/remote/main').initialize();

function createWindow() {
  const mainWindow = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      nodeIntegration: true, // 允许渲染进程使用Node.js API
      contextIsolation: false, // 关闭上下文隔离(让remote能正常工作)
      enableRemoteModule: true // Electron 10-13版本需要加这个,14+靠上面的@electron/remote
    }
  });

  // 给当前窗口开启remote权限(Electron 14+必须加)
  require('@electron/remote/main').enable(mainWindow.webContents);

  // 把用户名挂载到全局变量,不用写sendUName函数,直接挂就行
  global.uName = uName;

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

app.whenReady().then(() => {
  createWindow();
  app.on('activate', () => {
    if (BrowserWindow.getAllWindows().length === 0) createWindow();
  });
});

第二步:修改index.html

现在不用browserify,直接写就行:

<html>
<head>
  <script>
    const { remote } = require('electron');
    // 直接从主进程全局变量里拿用户名
    const currentUser = remote.getGlobal('uName');
    document.write(`当前登录用户:${currentUser}`);
  </script>
</head>
<body></body>
</html>

方案2:官方推荐的IPC通信(更安全)

其实IPC才是Electron官方建议的跨进程通信方式,尤其是你需要开启上下文隔离(更安全,防止XSS攻击)的时候,之前你尝试IPC没成功,大概率是步骤没做全,我给你写完整流程:

第一步:修改main.js

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

var uName = username.sync();

function createWindow() {
  const mainWindow = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      contextIsolation: true, // 开启上下文隔离(安全最佳实践)
      preload: path.join(__dirname, 'preload.js') // 指定预加载脚本
    }
  });

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

// 监听渲染进程的请求,返回用户名
ipcMain.handle('get-user-name', () => {
  return uName;
});

app.whenReady().then(() => {
  createWindow();
  app.on('activate', () => {
    if (BrowserWindow.getAllWindows().length === 0) createWindow();
  });
});

第二步:新建preload.js文件(和main.js同目录)

这个脚本是在渲染进程加载前运行的,用来安全地暴露API给页面:

const { contextBridge, ipcRenderer } = require('electron');

// 给页面暴露一个安全的API,只能调用我们允许的方法
contextBridge.exposeInMainWorld('electronAPI', {
  getUsername: () => ipcRenderer.invoke('get-user-name')
});

第三步:修改index.html

现在页面里不用require,直接调用暴露的API就行:

<html>
<head>
  <script>
    // 因为是异步调用,所以用async/await
    async function showUsername() {
      const username = await window.electronAPI.getUsername();
      document.write(`当前登录用户:${username}`);
    }
    // 页面加载时调用
    showUsername();
  </script>
</head>
<body></body>
</html>

关于你之前用browserify的问题

browserify确实能把Node.js的require打包成浏览器能识别的代码,但这完全是绕远路——Electron的渲染进程本身就支持Node.js API,只要配置对就行,而且用IPC的方案更安全,也符合Electron的设计规范。


内容的提问来源于stack exchange,提问作者Ab dul Salam

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 08:01:15