| 在 Windows 下有两种常见方式让 Electron 以“管理员”运行: 方案一:打包时给 exe 加 UAC 清单(每次启动都会弹 UAC) 复制代码{
  "build": {
    "appId": "com.example.app",
    "win": {
      "target": ["nsis"],
      "requestedExecutionLevel": "requireAdministrator"   // 关键:要求管理员
    },
    "nsis": {
      "perMachine": true                                   // 安装器需要管理员(可选)
    }
  }
}
说明 每次运行主程序都会触发 UAC 提升。若只想安装器提权,把 requestedExecutionLevel 去掉,仅保留 nsis.perMachine。
 方案二:运行时检测并“自我重启”到管理员(按需提升,推荐) 启动时判断当前是否已提权;未提权则用 runas 重新拉起自己并退出原进程。
 复制代码// main process
const { app } = require('electron');
const { spawn } = require('child_process');
const isElevated = require('is-elevated'); // npm i is-elevated
async function relaunchAsAdminIfNeeded() {
  if (process.platform !== 'win32') return;
  if (await isElevated()) return;
  // 重新以管理员启动自己(保留参数)
  const args = process.argv.slice(1).map(a => `"${a}"`).join(' ');
  const ps = [
    '-NoProfile','-Command',
    `Start-Process -FilePath "${process.execPath}" -ArgumentList '${args.replace(/'/g, "''")}' -Verb runAs`
  ];
  spawn('powershell.exe', ps, { detached: true, windowsHide: true });
  app.quit();
}
app.whenReady().then(relaunchAsAdminIfNeeded);
补充 electron-forge/packager:没有内置 requestedExecutionLevel,需要在打包后用 rcedit 加清单,或改用 electron-builder。无法绕过 UAC:管理员启动必须得到用户同意。若只需个别操作提权,别让主程序一直以管理员运行;改为单独拉起提权的子进程或使用 sudo-prompt/electron-elevate。
 |