如何拦截针对文件的请求并将其更改为 http 协议?

Rop*_*sai 5 electron

在 Electron 中,是否可以拦截针对 file:/// 的请求并将其重定向到 http?

我检查了 Electron协议页面,但是否支持尚不清楚。

Luk*_*non 2

您可以将protocol.registerHttpProtocol与方案一起使用file来拦截file:请求,然后发出 HTTP 请求。

示例(未经测试):

const {app, protocol} = require('electron')
const path = require('path')

app.on('ready', () => {
  protocol.registerHttpProtocol('file', (request, callback) => {
    const url = request.url.substr(8)
    callback({url: 'http://example.com/' + url)})
  }, (error) => {
    if (error) console.error('Failed to register protocol')
  })
})
Run Code Online (Sandbox Code Playgroud)

注意:此示例可能需要改进,因为文件路径可能包含驱动器号,这对于 HTTP 请求无效。