1、有个小需求:在electron项目中展示一个本地pdf文档;
2、实现:根据网上资料,需要注册一个类似file://的协议来访问本地文件,界面使用iframe显示pdf文件,具体代码如下:
(1)注册app://协议,pdf文件放在项目的public目录下
protocol.registerFileProtocol('app', (request, callback) => {
const url = request.url.replace('app://', ''); // 移除协议前缀
const filePath = path.join(app.getAppPath(), 'public', url); // 映射到项目内的 public 目录
console.log('filePath', filePath);
callback({ path: filePath });
});
(2)前端显示: 1.pdf在项目根目录的public路径下
{<iframe
src="app://1.pdf"
title="pdf文档"
style={{ width: "100%", height: "500px", border: 'none' }}
onError={(e) => console.error('pdf加载错误:', e)}
/>}
(3)electron-forge配置中增加策略
devContentSecurityPolicy = `xxx; frame-src 'self' app:`
3、结果:
(1)主进程log打印的pdf文件完整路径没问题;
(2)主进程报错如下:
[27620:0502/170320.052:ERROR:bad_message.cc(29)] Terminating renderer for bad IPC message, reason 1
(3)前端控制台和network也不报错,界面不显示pdf

(4)将pdf文件修改成图片或文本文件时,显示正常;
所以,pdf能这样显示吗,问题在哪?