Electron 自定义协议与静态资源加载
概述
本项目使用两个自定义协议实现 Electron 环境下的页面加载和静态资源访问:
| 协议 | 用途 | standard | 映射目录 |
|---|---|---|---|
limapp:// | 页面加载(主应用 HTML) | true | dist-electron-renderer/ |
limasset:// | 静态资源(主题/emoji/图标) | false | resources/assets/ |
limfile:// | 文件预览(本地/缓存文件, 流式只读;URL 必须带 host, 见 2.2) | true | 任意本地绝对路径 |
一、协议注册(主进程 index.ts)
1.1 注册特权协议(app.whenReady 之前)
ts
// ⚠️ 必须在 app.whenReady() 之前调用
// ⚠️ 只能调用一次!分段调用时后一次会使前一次注册的 scheme 特权失效
// (典型症状:打包环境 limfile:// fetch 报 "URL scheme is not supported",dev 却正常)
// → 所有协议收集到一个数组,最后一次性注册
const privilegedSchemes: Electron.CustomScheme[] = [
{
// 文件预览专用(任意本地文件只读映射, 支持 fetch/流式/拖动进度)
// dev 与 prod 都需注册(预览窗口 dev 从 vite server 加载, 同样以 limfile:// 读本地文件)
// ⚠️ URL 生成必须带 host(toFileUrl → limfile://local/C:/...):
// 空 host 时 Windows 盘符会被 Chromium 提升为 hostname 而丢失(见 2.2)
scheme: "limfile",
privileges: {
standard: true,
secure: true,
supportFetchAPI: true,
corsEnabled: true,
stream: true,
},
},
];
if (!VITE_DEV_SERVER_URL) {
privilegedSchemes.push(
{
scheme: "limapp",
privileges: {
standard: true, // 页面协议需要 standard(支持相对路径、同源策略)
secure: true,
supportFetchAPI: true,
corsEnabled: true,
},
},
{
scheme: "limasset",
privileges: {
// ⚠️ 资源协议不要加 standard: true!
// 否则 limasset:///path 的第一个路径段会被 Chromium 当成 hostname
secure: true,
supportFetchAPI: true,
corsEnabled: true,
bypassCSP: true,
},
},
);
}
protocol.registerSchemesAsPrivileged(privilegedSchemes);1.2 注册协议处理器(app.whenReady 之后)
ts
app.whenReady().then(async () => {
// limapp:// → dist-electron-renderer 目录
protocol.handle("limapp", (request) => {
const url = new URL(request.url);
let pathname = url.pathname.replace(/^\//, "").replace(/\/$/, "");
if (!pathname || pathname.endsWith("/")) {
pathname = pathname ? pathname + "index.html" : "index.html";
}
const filePath = path.normalize(path.join(RENDERER_DIST, pathname));
return net.fetch(pathToFileURL(filePath).href);
});
// limasset:// → resources/assets 目录
protocol.handle("limasset", (request) => {
const url = new URL(request.url);
const pathname = decodeURIComponent(url.pathname.replace(/^\/+/, ""));
let filePath: string;
if (pathname.startsWith("user-theme/")) {
const rest = pathname.replace(/^user-theme\//, "");
filePath = path.normalize(path.join(app.getPath("userData"), "themes", rest));
} else {
const publicPath = app.isPackaged
? path.join(process.resourcesPath, "assets")
: path.join(process.cwd(), "public");
filePath = path.normalize(path.join(publicPath, pathname));
}
return net.fetch(pathToFileURL(filePath).href);
});
});1.3 关键导入
ts
import { app, BrowserWindow, protocol, net } from "electron";
import path from "node:path";
import { pathToFileURL } from "node:url"; // ⚠️ 必须用 pathToFileURL,不能手动拼 file:// URL二、URL 格式规范
2.1 正确的 URL 格式
limasset:///theme/default/bg.png ✅ 三斜杠,空 host(limasset 无 standard, 不做 host 分解)
limasset:///emojiGroups/pupu/emoji/1.png ✅
limapp:///index.html ✅ 页面协议用 standard:true,三斜杠OK
limfile://local/C:/dir/a.png ✅ standard:true 必须带 host(固定 "local")
limfile:///C:/dir/a.png ❌ 空 host: 盘符 "C:" 被当 hostname, pathname 丢失盘符2.2 为什么资源协议不能用 standard: true
当 standard: true 时,Chromium 按 RFC 3986 解析 URL:
limasset:///theme/default/bg.png
│ │
│ └── 空 host → Chromium 把 "theme" 当成 hostname
│ pathname 变成 /default/bg.png(丢失 theme/)
└── scheme去掉 standard: true 后,URL 不做 host/path 分解,pathname 完整保留。
limapp:// 为什么可以 standard: true? 因为 limapp:///index.html 中 index.html 只有一段,不存在"第一路径段被吃"的问题。
limfile:// 的另一种解法:保留 standard: true + 显式 host
文件预览需要 standard 语义,URL 由 toFileUrl() 统一生成 limfile://local/C:/...(host 固定 local):
limfile://local/C:/Users/x/cache/downloads/a.png
│ │ └── pathname="/C:/Users/..." → 主进程 slice(1) 得 C:/Users/...
│ └── 固定 host(必须有!)
└── scheme- 空 host 时 Windows 盘符
C:会被提升为 hostname(:被当 host:port 分隔 → host=c),pathname 丢失盘符 - 主进程按丢失盘符的 pathname 解析 →
pathToFileURL()补到 进程当前盘 → 文件不存在 → fetch 报net::ERR_UNEXPECTED - ⚠️ 该 bug dev 环境会被掩盖:dev 缓存目录在项目目录(APP_ROOT/cache),与 cwd 同盘,错误补全恰好命中;打包环境缓存位于
%APPDATA%(C 盘)而 cwd 在安装目录,盘符错位才暴露 - POSIX:
limfile://local/home/user/a.md→ pathname/home/user/a.md,主进程保留前导斜杠
三、file:// URL 构造
3.1 必须用 pathToFileURL()
ts
// ✅ 正确:自动处理路径编码(空格、中文等)
import { pathToFileURL } from "node:url";
return net.fetch(pathToFileURL(filePath).href);
// → file:///D:/Program%20Files/%E9%80%94%E8%A1%8C%E8%80%852/resources/...
// ❌ 错误:手动拼接不做编码,中文路径导致 ERR_UNEXPECTED
return net.fetch("file:///" + filePath.replace(/\\/g, "/"));
// → file:///D:/Program Files/LIM2/resources/... ← 空格和中文未编码四、生产环境资源路径
4.1 用 process.resourcesPath,不用 app.getPath('exe')
ts
// ✅ 正确:直接指向 <installDir>/resources/
path.join(process.resourcesPath, "assets", "emojiGroups")
// ❌ 错误:Electron 40+ 中 path.dirname(app.getPath('exe')) 可能返回意外路径
path.join(path.dirname(app.getPath('exe')), "resources", "assets", "emojiGroups")4.2 双环境路径策略
| 场景 | 开发环境 | 生产环境 |
|---|---|---|
| 资源根目录 | <项目根>/public/ | <installDir>/resources/assets/ |
| URL 前缀 | /path(Vite dev server) | limasset:///path |
| JSON 读取 | process.cwd()/public/... | process.resourcesPath/assets/... |
五、渲染进程 URL 生成函数
5.1 emojiAssetUrl()(emoji 图片 URL)
位置:src/renderer/apps/main/views/chat/components/emoji/utils.ts
ts
export function emojiAssetUrl(relPath: string): string {
return import.meta.env.DEV
? `/${relPath}` // dev: /emojiGroups/pupu/emoji/1.png
: `limasset:///${relPath}` // prod: limasset:///emojiGroups/pupu/emoji/1.png
}使用方式:
ts
emojiAssetUrl(`emojiGroups/${groupId}/emoji/${fileName}`)
emojiAssetUrl(`emojiGroups/${groupId}/emojiAnimate/${animatedFileName}`)
emojiAssetUrl(`emojiGroups/${groupId}/icon.png`)5.2 getAssetPath()(通用资源 URL)
位置:src/main/core/config-store.ts
ts
export function getAssetPath(relativePath: string): string {
const normalizedPath = relativePath.replace(/\\/g, '/');
return `limasset:///${normalizedPath}`;
}用于主题背景图 URL 生成:
ts
const relativePath = source === 'builtin'
? `theme/${meta.id}/bg.png`
: `user-theme/${meta.id}/bg.png`;
background = getAssetPath(relativePath);
// → limasset:///theme/default/bg.png六、JSON 配置文件读取(走 IPC,不走协议)
6.1 为什么 JSON 不走 limasset:// 协议
fetch("limasset:///...")受 CSPconnect-src限制- dev 模式下 limasset 未注册特权协议,fetch 报 "URL scheme is not supported"
- 走 IPC 由主进程根据
app.isPackaged选路径,dev/prod 行为一致
6.2 IPC 通道
| 项目 | 值 |
|---|---|
| 通道名 | emoji:read-json-file |
| 主进程文件 | src/main/ipc/emoji-assets.ts |
| preload 暴露 | window.electronAPI.readEmojiJsonFile(relPath) |
| 渲染进程封装 | readEmojiJson<T>(relPath) in utils.ts |
6.3 渲染进程使用
ts
export async function readEmojiJson<T = unknown>(relPath: string): Promise<T> {
const result = await window.electronAPI.readEmojiJsonFile(relPath);
if (!result.success) {
throw new Error(result.error || "读取 emoji 资源失败");
}
return JSON.parse(result.data) as T;
}
// 使用示例
const groups = await readEmojiJson<EmojiGroupsIndex>('groups.json');
const config = await readEmojiJson<EmojiGroupConfig>(`${groupId}/config.json`);6.4 主进程 IPC Handler
ts
// src/main/ipc/emoji-assets.ts
function getEmojiGroupsDir(): string {
if (app.isPackaged) {
return path.join(process.resourcesPath, 'assets', 'emojiGroups');
}
return path.join(process.cwd(), 'public', 'emojiGroups');
}
ipcMain.handle(IPC_EMOJI_READ_JSON, async (_event, relPath: string) => {
const filePath = safeJoin(getEmojiGroupsDir(), relPath); // 防 path traversal
const content = await fs.readFile(filePath, 'utf-8');
return { success: true, data: content };
});七、CSP 配置
每个 HTML 页面的 <meta> 标签中必须包含 limasset://*:
html
<meta http-equiv="Content-Security-Policy"
content="default-src 'self' ... limasset://*;
img-src 'self' data: blob: ... limasset://* https://*;
style-src 'self' 'unsafe-inline' ... limasset://*;
connect-src 'self' ... limasset://* ...;" />需要 limasset://* 的 CSP 指令:
| 指令 | 说明 |
|---|---|
default-src | 兜底策略 |
img-src | <img> 标签加载 emoji/主题图片 |
style-src | CSS url() 加载背景图 |
connect-src | 如果有 fetch(limasset://...) 调用 |
八、electron-builder 打包配置
8.1 extraResources(资源文件不打入 asar)
json5
extraResources: [
{
from: "public/theme/",
to: "./assets/theme/", // → resources/assets/theme/
filter: ["**/*"],
},
{
from: "public/emojiGroups/",
to: "./assets/emojiGroups/", // → resources/assets/emojiGroups/
filter: ["**/*"],
},
{
from: "./electron-build/icons/",
to: "./icons/", // → resources/icons/
filter: ["**/*"],
},
]8.2 to 路径规则
to相对于resources/目录./assets/xxx/→ 文件放到resources/assets/xxx/- ⚠️ 不要用
../,那会把文件放到resources/外面
8.3 打包后目录结构
<installDir>/
├── LIM2.exe
├── resources/
│ ├── app.asar ← 主进程+渲染进程代码
│ ├── assets/
│ │ ├── theme/
│ │ │ ├── default/
│ │ │ │ ├── theme.json ← background: "limasset:///theme/default/bg.png"
│ │ │ │ └── bg.png
│ │ │ ├── dark/
│ │ │ └── starry/
│ │ └── emojiGroups/
│ │ ├── groups.json
│ │ └── pupu/
│ │ ├── config.json
│ │ ├── icon.png
│ │ ├── emoji/
│ │ └── emojiAnimate/
│ └── icons/
│ └── logo.ico九、常见陷阱速查
| 陷阱 | 症状 | 修复 |
|---|---|---|
standard: true + 空 host | 路径第一段被当 hostname:① 资源路径(limasset:///theme/... 的 theme/);② Windows 盘符 C: → pathname 丢盘符 → 打包版 fetch net::ERR_UNEXPECTED(dev 常被同盘 cwd 掩盖) | ① 资源协议去掉 standard: true(limasset 模式);② URL 显式带 host(limfile 模式: limfile://local/C:/...) |
手动拼 file:/// URL | 中文路径 ERR_UNEXPECTED | 用 pathToFileURL(filePath).href |
path.dirname(app.getPath('exe')) | 返回路径多了子目录 | 用 process.resourcesPath |
extraResources to: "../xxx" | 文件放到 resources 外面 | 改成 to: "./xxx" |
fetch("limasset:///...") | CSP 拦截或 dev 模式不支持 | JSON 走 IPC,图片走 <img> |
CSP 缺少 limasset://* | 图片/背景图被浏览器拦截 | 在 img-src/style-src 等添加 |
registerSchemesAsPrivileged 分段多次调用 | 后次调用使前次注册的 scheme 特权失效(打包后 limfile:// fetch 报 URL scheme "limfile" is not supported,而 dev 正常——因 dev 不执行 limapp/limasset 分支) | 所有协议合并到单次调用 |
十、涉及文件清单
| 文件 | 作用 |
|---|---|
src/main/index.ts | 协议注册(registerSchemesAsPrivileged + protocol.handle) |
src/main/ipc/emoji-assets.ts | emoji JSON 读取 IPC handler |
src/main/ipc/index.ts | IPC 统一注册入口 |
src/main/core/config-store.ts | 主题管理 + getAssetPath() URL 生成 |
src/preload/index.ts | preload 暴露 readEmojiJsonFile API |
src/electron-env.d.ts | 渲染进程类型声明(window.electronAPI) |
src/renderer/.../emoji/utils.ts | emojiAssetUrl() + readEmojiJson() |
src/renderer/.../emoji/EmojiPicker.vue | emoji 面板(主窗口内嵌) |
src/renderer/apps/emoji-picker/EmojiPickerView.vue | emoji 面板(独立窗口) |
src/renderer/apps/*/index.html | 各窗口 CSP 配置 |
public/theme/*/theme.json | 主题配置(background 字段用 limasset:/// URL) |
electron-build/electron-builder.json5 | extraResources 打包配置 |