protocol
注册自定义协议并拦截现有协议请求。
进程:主进程
实现一个与 file://
协议具有相同效果的协议的示例
const { app, protocol, net } = require('electron')
const path = require('node:path')
const url = require('node:url')
app.whenReady().then(() => {
protocol.handle('atom', (request) => {
const filePath = request.url.slice('atom://'.length)
return net.fetch(url.pathToFileURL(path.join(__dirname, filePath)).toString())
})
})
注意:除非另有说明,所有方法只能在 app
模块的 ready
事件触发后使用。
使用自定义 partition
或 session
的 protocol
协议会注册到一个特定的 Electron session
对象上。 如果您不指定 session,那么您的 protocol
将应用于 Electron 使用的默认 session。 但是,如果您在 browserWindow
的 webPreferences
上定义了 partition
或 session
,那么该窗口将使用不同的 session,并且如果您只使用 electron.protocol.XXX
,您的自定义协议将不起作用。
要使您的自定义协议与自定义 session 结合使用,您需要将其显式注册到该 session。
const { app, BrowserWindow, net, protocol, session } = require('electron')
const path = require('node:path')
const url = require('url')
app.whenReady().then(() => {
const partition = 'persist:example'
const ses = session.fromPartition(partition)
ses.protocol.handle('atom', (request) => {
const filePath = request.url.slice('atom://'.length)
return net.fetch(url.pathToFileURL(path.resolve(__dirname, filePath)).toString())
})
const mainWindow = new BrowserWindow({ webPreferences: { partition } })
})
方法
protocol
模块具有以下方法
protocol.registerSchemesAsPrivileged(customSchemes)
customSchemes
CustomScheme[]
注意:此方法只能在 app
模块的 ready
事件触发前使用,且只能调用一次。
将 scheme
注册为标准协议,使其安全、绕过资源的 CSP、允许注册 ServiceWorker、支持 fetch API、视频/音频流以及 V8 代码缓存。 使用值 true
指定特权以启用功能。
注册一个绕过内容安全策略的特权协议的示例
const { protocol } = require('electron')
protocol.registerSchemesAsPrivileged([
{ scheme: 'foo', privileges: { bypassCSP: true } }
])
标准协议遵循 RFC 3986 中称为 通用 URI 语法 的规范。 例如,http
和 https
是标准协议,而 file
则不是。
将协议注册为标准协议后,可以正确解析相对和绝对资源。 否则,该协议将表现得像 file
协议,但无法解析相对 URL。
例如,当您使用自定义协议加载以下页面而未将其注册为标准协议时,图像将无法加载,因为非标准协议无法识别相对 URL
<body>
<img src='test.png'>
</body>
将协议注册为标准协议后,可以通过 FileSystem API 访问文件。 否则,渲染器将针对该协议抛出安全错误。
默认情况下,网页存储 API (localStorage, sessionStorage, webSQL, indexedDB, cookies) 对于非标准协议是禁用的。 因此,通常情况下,如果您想注册一个自定义协议来替换 http
协议,您必须将其注册为标准协议。
使用流 (http 和 stream 协议) 的协议应设置 stream: true
。 <video>
和 <audio>
HTML 元素默认期望协议对其响应进行缓冲。 stream
标志配置这些元素以正确地期望流式响应。
protocol.handle(scheme, handler)
scheme
string - 要处理的协议方案,例如https
或my-app
。 这是 URL 中:
之前的部分。handler
Function<GlobalResponse | Promise<GlobalResponse>>request
GlobalRequest
为 scheme
注册一个协议处理程序。 发送到使用此 scheme 的 URL 的请求将委托给此处理程序来确定应发送何种响应。
可以返回 Response
或 Promise<Response>
。
示例
const { app, net, protocol } = require('electron')
const path = require('node:path')
const { pathToFileURL } = require('url')
protocol.registerSchemesAsPrivileged([
{
scheme: 'app',
privileges: {
standard: true,
secure: true,
supportFetchAPI: true
}
}
])
app.whenReady().then(() => {
protocol.handle('app', (req) => {
const { host, pathname } = new URL(req.url)
if (host === 'bundle') {
if (pathname === '/') {
return new Response('<h1>hello, world</h1>', {
headers: { 'content-type': 'text/html' }
})
}
// NB, this checks for paths that escape the bundle, e.g.
// app://bundle/../../secret_file.txt
const pathToServe = path.resolve(__dirname, pathname)
const relativePath = path.relative(__dirname, pathToServe)
const isSafe = relativePath && !relativePath.startsWith('..') && !path.isAbsolute(relativePath)
if (!isSafe) {
return new Response('bad', {
status: 400,
headers: { 'content-type': 'text/html' }
})
}
return net.fetch(pathToFileURL(pathToServe).toString())
} else if (host === 'api') {
return net.fetch('https://api.my-server.com/' + pathname, {
method: req.method,
headers: req.headers,
body: req.body
})
}
})
})
请参阅 MDN 文档中关于 Request
和 Response
的详细信息。
protocol.unhandle(scheme)
scheme
string - 要移除处理程序的协议方案。
移除使用 protocol.handle
注册的协议处理程序。
protocol.isProtocolHandled(scheme)
scheme
string
返回 boolean
- scheme
是否已被处理。
protocol.registerFileProtocol(scheme, handler)
已废弃
scheme
stringhandler
Functionrequest
ProtocolRequestcallback
Functionresponse
(string | ProtocolResponse)
返回 boolean
- 协议是否已成功注册
注册一个 scheme
协议,它将发送文件作为响应。 handler
将使用 request
和 callback
调用,其中 request
是对 scheme
的传入请求。
为了处理 request
,应使用文件路径或具有 path
属性的对象调用 callback
,例如 callback(filePath)
或 callback({ path: filePath })
。 filePath
必须是绝对路径。
默认情况下,scheme
被视为 http:
,这与遵循“通用 URI 语法”的协议(如 file:
)的解析方式不同。
protocol.registerBufferProtocol(scheme, handler)
已废弃
scheme
stringhandler
Functionrequest
ProtocolRequestcallback
Functionresponse
(Buffer | ProtocolResponse)
返回 boolean
- 协议是否已成功注册
注册一个 scheme
协议,它将发送 Buffer
作为响应。
用法与 registerFileProtocol
相同,但 callback
应使用 Buffer
对象或具有 data
属性的对象调用。
示例
protocol.registerBufferProtocol('atom', (request, callback) => {
callback({ mimeType: 'text/html', data: Buffer.from('<h5>Response</h5>') })
})
protocol.registerStringProtocol(scheme, handler)
已废弃
scheme
stringhandler
Functionrequest
ProtocolRequestcallback
Functionresponse
(string | ProtocolResponse)
返回 boolean
- 协议是否已成功注册
注册一个 scheme
协议,它将发送 string
作为响应。
用法与 registerFileProtocol
相同,但 callback
应使用 string
或具有 data
属性的对象调用。
protocol.registerHttpProtocol(scheme, handler)
已废弃
scheme
stringhandler
Functionrequest
ProtocolRequestcallback
Functionresponse
ProtocolResponse
返回 boolean
- 协议是否已成功注册
注册一个 scheme
协议,它将发送一个 HTTP 请求作为响应。
用法与 registerFileProtocol
相同,但 callback
应使用具有 url
属性的对象调用。
protocol.registerStreamProtocol(scheme, handler)
已废弃
scheme
stringhandler
Functionrequest
ProtocolRequestcallback
Functionresponse
(ReadableStream | ProtocolResponse)
返回 boolean
- 协议是否已成功注册
注册一个 scheme
协议,它将发送流作为响应。
用法与 registerFileProtocol
相同,但 callback
应使用 ReadableStream
对象或具有 data
属性的对象调用。
示例
const { protocol } = require('electron')
const { PassThrough } = require('stream')
function createStream (text) {
const rv = new PassThrough() // PassThrough is also a Readable stream
rv.push(text)
rv.push(null)
return rv
}
protocol.registerStreamProtocol('atom', (request, callback) => {
callback({
statusCode: 200,
headers: {
'content-type': 'text/html'
},
data: createStream('<h5>Response</h5>')
})
})
可以传递任何实现可读流 API(发出 data
/end
/error
事件)的对象。 例如,这是一个如何返回文件的示例
protocol.registerStreamProtocol('atom', (request, callback) => {
callback(fs.createReadStream('index.html'))
})
protocol.unregisterProtocol(scheme)
已废弃
scheme
string
返回 boolean
- 协议是否已成功注销
注销 scheme
的自定义协议。
protocol.isProtocolRegistered(scheme)
已废弃
scheme
string
返回 boolean
- scheme
是否已被注册。
protocol.interceptFileProtocol(scheme, handler)
已废弃
scheme
stringhandler
Functionrequest
ProtocolRequestcallback
Functionresponse
(string | ProtocolResponse)
返回 boolean
- 协议是否已成功拦截
拦截 scheme
协议,并使用 handler
作为协议的新处理程序,该处理程序将发送文件作为响应。
protocol.interceptStringProtocol(scheme, handler)
已废弃
scheme
stringhandler
Functionrequest
ProtocolRequestcallback
Functionresponse
(string | ProtocolResponse)
返回 boolean
- 协议是否已成功拦截
拦截 scheme
协议,并使用 handler
作为协议的新处理程序,该处理程序将发送 string
作为响应。
protocol.interceptBufferProtocol(scheme, handler)
已废弃
scheme
stringhandler
Functionrequest
ProtocolRequestcallback
Functionresponse
(Buffer | ProtocolResponse)
返回 boolean
- 协议是否已成功拦截
拦截 scheme
协议,并使用 handler
作为协议的新处理程序,该处理程序将发送 Buffer
作为响应。
protocol.interceptHttpProtocol(scheme, handler)
已废弃
scheme
stringhandler
Functionrequest
ProtocolRequestcallback
Functionresponse
ProtocolResponse
返回 boolean
- 协议是否已成功拦截
拦截 scheme
协议,并使用 handler
作为协议的新处理程序,该处理程序将发送新的 HTTP 请求作为响应。
protocol.interceptStreamProtocol(scheme, handler)
已废弃
scheme
stringhandler
Functionrequest
ProtocolRequestcallback
Functionresponse
(ReadableStream | ProtocolResponse)
返回 boolean
- 协议是否已成功拦截
与 protocol.registerStreamProtocol
相同,但它替换现有的协议处理程序。
protocol.uninterceptProtocol(scheme)
已废弃
scheme
string
返回 boolean
- 协议是否已成功取消拦截
移除为 scheme
安装的拦截器并恢复其原始处理程序。
protocol.isProtocolIntercepted(scheme)
已废弃
scheme
string
返回 boolean
- scheme
是否已被拦截。