欢迎加入开源鸿蒙PC社区:https://harmonypc.csdn.net

🔍 问题现象

你的 Hawkpass 应用在鸿蒙平台上运行时出现白屏,窗口正常打开但内容为空白。


🎯 根本原因

问题代码

// main.js
function createWindow() {
 const win = new BrowserWindow({
   width: 1024,
   height: 768,
   webPreferences: {
     nodeIntegration: true,  // ⚠️ 安全问题
  },
});
​
 win.loadFile('dist/index.html');  // ❌ 问题所在
}

原因分析

  1. 缺少构建产物:

    • 应用加载 dist/index.html

    • 这个文件需要通过 npm run build 生成

    • 没有构建就没有 dist/ 目录 → 白屏

  2. 应用技术栈:

    React + Parcel 构建工具
    ├── 源码在 src/
    ├── 需要打包到 dist/
    └── Electron 加载 dist/index.html
  3. 构建流程缺失:

    • 开发环境: npm run develop (浏览器预览)

    • 生产构建: npm run build (生成 dist/)

    • 运行应用: npm start (启动 Electron)


✅ 解决方案

方案 1: 构建应用(标准流程)

步骤 1: 安装依赖
cd /Users/jianguo/Desktop/harmony/electron/libelectron/ohos_hap/web_engine/src/main/resources/resfile/resources/app
​
# 安装 npm 依赖
npm install
步骤 2: 构建项目
# 生成 dist/ 目录
npm run build

构建后的目录结构:

app/
├── src/                 # 源代码
├── dist/                 # ✅ 构建产物
│   ├── index.html       # 打包后的 HTML
│   ├── index.*.js       # 打包后的 JS
│   └── index.*.css     # 打包后的 CSS
└── main.js             # Electron 主进程
步骤 3: 在鸿蒙上运行

构建完成后,使用 DevEco Studio 重新运行应用。


方案 2: 修改为加载本地源文件(临时方案)

如果构建失败或想快速测试,可以修改 main.js:

const { app, BrowserWindow, Menu } = require('electron');
const path = require('path');
​
function createWindow() {
 const win = new BrowserWindow({
   width: 1024,
   height: 768,
   webPreferences: {
     nodeIntegration: false,      // ✅ 安全改进
     contextIsolation: true,      // ✅ 启用隔离
     preload: path.join(__dirname, 'preload.js')  // ✅ 使用 preload
  },
});
​
 // ✅ 修改:加载 src 下的源文件
 win.loadFile('src/index.html');
 
 // ✅ 开发时打开 DevTools 调试
 win.webContents.openDevTools();
}
​
// ... 其余代码不变

注意: 这个方案需要确保 src/index.html 中引用的 JS/CSS 路径正确。


方案 3: 创建简单测试页面

创建一个简单的测试页面验证 Electron 是否正常工作:

// main.js
function createWindow() {
 const win = new BrowserWindow({
   width: 1024,
   height: 768,
   webPreferences: {
     nodeIntegration: false,
     contextIsolation: true,
  },
});
​
 // ✅ 直接加载 URL 或简单 HTML
 win.loadURL('https://www.electronjs.org/zh/docs/latest/');
 
 // 或者创建一个简单的 test.html
 // win.loadFile('test.html');
}

创建 test.html:

<!DOCTYPE html>
<html>
<head>
   <meta charset="UTF-8">
   <title>测试页面</title>
   <style>
       body {
           font-family: Arial, sans-serif;
           display: flex;
           justify-content: center;
           align-items: center;
           height: 100vh;
           margin: 0;
           background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
           color: white;
      }
       .container {
           text-align: center;
      }
       h1 {
           font-size: 48px;
           margin-bottom: 20px;
      }
   </style>
</head>
<body>
   <div class="container">
       <h1>✅ Electron 正常运行</h1>
       <p>如果你看到这个页面,说明 Electron 在鸿蒙上工作正常</p>
       <p>Chrome 版本: <span id="chrome"></span></p>
       <p>Node 版本: <span id="node"></span></p>
       <p>Electron 版本: <span id="electron"></span></p>
   </div>
   <script>
       // 注意:如果启用了 contextIsolation,需要通过 preload 访问
       if (typeof process !== 'undefined') {
           document.getElementById('chrome').textContent = process.versions.chrome;
           document.getElementById('node').textContent = process.versions.node;
           document.getElementById('electron').textContent = process.versions.electron;
      }
   </script>
</body>
</html>

🔧 调试技巧

1. 检查文件是否存在

# 检查 dist 目录
ls -la dist/

# 如果 dist 不存在或为空,需要构建
npm run build

2. 查看 Electron 控制台

main.js 中添加调试代码:

function createWindow() {
  const win = new BrowserWindow({
    // ... 配置
  });

  // 加载文件
  win.loadFile('dist/index.html');
  
  // 监听加载失败
  win.webContents.on('did-fail-load', (event, errorCode, errorDescription) => {
    console.error('页面加载失败:', errorCode, errorDescription);
  });
  
  // 监听加载完成
  win.webContents.on('did-finish-load', () => {
    console.log('页面加载成功');
  });
  
  // 打开 DevTools
  win.webContents.openDevTools();
}

3. 查看 DevEco Studio 日志

在 DevEco Studio 的 Log 面板中查看输出,可能会看到类似错误:

Error: ENOENT: no such file or directory, open 'dist/index.html'

🎯 Hawkpass 应用特定说明

应用简介

Hawkpass 是一个密码生成器应用,功能包括:

  • 🎲 使用 Diceware 方法生成安全密码

  • 🖱️ 通过鼠标移动收集熵

  • 🔐 SHA-256 加密随机数生成

  • 🌍 支持多种语言的词典

完整构建流程

# 1. 进入项目目录
cd /path/to/app

# 2. 安装依赖(首次)
npm install

# 3. 构建生产版本
npm run build

# 4. 验证构建产物
ls dist/
# 应该看到: index.html, index.*.js, index.*.css

# 5. 运行 Electron 应用
npm start

# 或者在鸿蒙上通过 DevEco Studio 运行

package.json 脚本说明

{
  "scripts": {
    "start": "electron-forge start",      // 启动 Electron
    "develop": "parcel src/index.html",   // 浏览器开发模式
    "build": "parcel build --public-url ./ src/index.html",  // 构建
    "package": "electron-forge package",  // 打包应用
    "make": "electron-forge make"         // 创建分发包
  }
}

⚠️ 安全问题修复

当前 main.js 中有安全隐患:

// ❌ 不安全的配置
webPreferences: {
  nodeIntegration: true,  // 允许渲染进程直接访问 Node.js
}

推荐修改为:

// ✅ 安全的配置
webPreferences: {
  nodeIntegration: false,
  contextIsolation: true,
  preload: path.join(__dirname, 'preload.js')
}

创建 preload.js:

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

// 只暴露必要的 API
contextBridge.exposeInMainWorld('electronAPI', {
  versions: {
    chrome: process.versions.chrome,
    node: process.versions.node,
    electron: process.versions.electron
  },
  platform: process.platform
});

📋 完整排查清单

问题排查步骤

  • 步骤 1: 检查 dist/ 目录是否存在
    ls -la dist/
  • 步骤 2: 如果不存在,运行构建
    npm install
    npm run build
  • 步骤 3: 验证构建产物
    ls dist/index.html  # 应该存在
  • 步骤 4: 检查 main.js 加载路径
    win.loadFile('dist/index.html');  // 路径是否正确
  • 步骤 5: 启用 DevTools 调试
    win.webContents.openDevTools();
  • 步骤 6: 查看控制台错误信息
  • 步骤 7: 检查文件权限(鸿蒙特定)
    chmod -R 755 dist/
  • 步骤 8: 验证 webPreferences 配置
    webPreferences: {
      nodeIntegration: false,      // ✅
      contextIsolation: true,      // ✅
    }

🎓 最佳实践

1. 开发流程

# 开发阶段
npm run develop  # 在浏览器中开发和测试

# 构建阶段
npm run build    # 生成生产构建

# 测试阶段
npm start        # 在 Electron 中测试

# 打包阶段
npm run make     # 创建分发包

2. 鸿蒙平台特殊处理

// main.js 中添加平台检测
function createWindow() {
  const isHarmonyOS = process.platform === 'harmonyos';
  
  const win = new BrowserWindow({
    width: 1024,
    height: 768,
    webPreferences: {
      nodeIntegration: false,
      contextIsolation: true,
    },
  });

  win.loadFile('dist/index.html');
  
  // 鸿蒙平台特殊配置
  if (isHarmonyOS) {
    win.setWindowButtonVisibility(true);
    // 其他鸿蒙特定配置
  }
}

3. 错误处理

async function createWindow() {
  const win = new BrowserWindow({ /* ... */ });

  try {
    await win.loadFile('dist/index.html');
    console.log('页面加载成功');
  } catch (error) {
    console.error('页面加载失败:', error);
    
    // 降级方案:加载错误页面
    win.loadURL(`data:text/html,
      <html>
        <body>
          <h1>应用加载失败</h1>
          <p>请确保已运行 npm run build</p>
          <pre>${error.message}</pre>
        </body>
      </html>
    `);
  }
}

🚀 自动化构建方案

创建一个启动脚本自动检查和构建:

start.sh:

#!/bin/bash

# 检查 dist 目录是否存在
if [ ! -d "dist" ]; then
    echo "⚠️  dist 目录不存在,开始构建..."
    npm run build
    
    if [ $? -eq 0 ]; then
        echo "✅ 构建成功"
    else
        echo "❌ 构建失败"
        exit 1
    fi
else
    echo "✅ dist 目录已存在"
fi

# 启动应用
echo "🚀 启动应用..."
npm start

package.json 中添加脚本:

{
  "scripts": {
    "start": "electron-forge start",
    "start:safe": "bash start.sh",     // 安全启动
    "prebuild": "rm -rf dist",          // 清理旧构建
    "build": "parcel build --public-url ./ src/index.html"
  }
}


📊 总结

白屏原因

原因 说明 解决方案
缺少构建产物 dist/ 目录不存在 运行 npm run build
路径错误 加载文件路径不对 修改 loadFile 路径
构建失败 依赖安装失败 运行 npm install
权限问题 文件权限不正确 chmod -R 755 dist/
React 错误 组件渲染失败 查看 DevTools 控制台

快速修复命令

# 一键修复流程
cd /path/to/app
npm install
npm run build
npm start

🔗 参考资源


作者: @jianguoxu 日期: 2025年11月 项目: Electron on HarmonyOS


💡 提示: 如果问题仍未解决,请检查 DevEco Studio 的日志输出,或在项目仓库提交 Issue!

Logo

开源鸿蒙跨平台开发社区汇聚开发者与厂商,共建“一次开发,多端部署”的开源生态,致力于降低跨端开发门槛,推动万物智联创新。

更多推荐