79553659

Date: 2025-04-03 17:56:00
Score: 0.5
Natty:
Report link

regist your protocol in main.js:




protocol.registerSchemesAsPrivileged([
  {
    scheme: 'local-resource',
    privileges: {
      secure: true,
      supportFetchAPI: true, // impotant
      standard: true,
      bypassCSP: true, // impotant
      stream: true 
    }
  }
])

then achieve protocol.handle func, pay attention to deal windows path drive letter.


app.whenReady().then(() => {
  // 一个辅助函数,用于处理不同操作系统的文件路径问题
  function convertPath(originalPath) {
    const match = originalPath.match(/^\/([a-zA-Z])\/(.*)$/)
    if (match) {
      // 为 Windows 系统转换路径格式 恢复盘符
      return `${match[1]}:/${match[2]}`
    } else {
      return originalPath // 其他系统直接使用原始路径
    }
  }

  // 自定义协议对接为file协议
  protocol.handle('local-resource', async (request) => {
    const decodedUrl = decodeURIComponent(
      request.url.replace(new RegExp(`^local-resource://`, 'i'), '/')
    )
    const fullPath = process.platform === 'win32' ? convertPath(decodedUrl) : decodedUrl
    return net.fetch(`file://${fullPath}`)
  })

  createWindow()

})







use it. vue syntax

<template>
  <img :src="`local-resource://E:/Download/tom.png`" />
</template>

ref https://docs.ffffee.com/electron/electron%E5%8A%A0%E8%BD%BD%E6%9C%AC%E5%9C%B0%E8%B5%84%E6%BA%90%E4%BE%8B%E5%AD%90.html

Reasons:
  • Probably link only (1):
  • Long answer (-1):
  • Has code block (-0.5):
  • Low reputation (1):
Posted by: Yong Huang