protocol
Register a custom protocol and intercept existing protocol requests.注册自定义协议并拦截现有的协议请求。
Process: 进程:Main
An example of implementing a protocol that has the same effect as the 实现与file://
protocol:file://
协议具有相同效果的协议的示例:
const { app, protocol } = require('electron')
const path = require('path')
app.whenReady().then(() => {
protocol.registerFileProtocol('atom', (request, callback) => {
const url = request.url.substr(7)
callback({ path: path.normalize(`${__dirname}/${url}`) })
})
})
Note: All methods unless specified can only be used after the 除非指定,否则所有方法只能在发出ready
event of the app
module gets emitted.app
模块的ready
事件后使用。
Using protocol
with a custom partition
or session
将protocol
与自定义partition
或session
一起使用
protocol
with a custom partition
or session
A protocol is registered to a specific Electron session object. 协议被注册到特定的Electronsession对象。If you don't specify a session, then your 如果您没有指定会话,那么protocol
will be applied to the default session that Electron uses. protocol
将应用于Electron使用的默认会话。However, if you define a 但是,如果您在partition
or session
on your browserWindow
's webPreferences
, then that window will use a different session and your custom protocol will not work if you just use electron.protocol.XXX
.browserWindow
的webPreferences
上定义了一个partition
或session
,那么该窗口将使用不同的会话,如果您只使用electron.protocol.XXX
,则您的自定义协议将不起作用。
To have your custom protocol work in combination with a custom session, you need to register it to that session explicitly.要使您的自定义协议与自定义会话结合使用,您需要将其显式注册到该会话。
const { session, app, protocol } = require('electron')
const path = require('path')
app.whenReady().then(() => {
const partition = 'persist:example'
const ses = session.fromPartition(partition)
ses.protocol.registerFileProtocol('atom', (request, callback) => {
const url = request.url.substr(7)
callback({ path: path.normalize(`${__dirname}/${url}`) })
})
mainWindow = new BrowserWindow({ webPreferences: { partition } })
})
Methods方法
The protocol
module has the following methods:protocol
模块有以下方法:
protocol.registerSchemesAsPrivileged(customSchemes)
customSchemes
CustomScheme[]
Note: This method can only be used before the 此方法只能在ready
event of the app
module gets emitted and can be called only once.app
模块的ready
事件发出之前使用,并且只能调用一次。
Registers the 将该scheme
as standard, secure, bypasses content security policy for resources, allows registering ServiceWorker, supports fetch API, and streaming video/audio. scheme
注册为标准、安全、绕过资源的内容安全策略、允许注册ServiceWorker、支持fetch API和流式视频/音频。Specify a privilege with the value of 指定一个值为true
to enable the capability.true
的特权以启用该功能。
An example of registering a privileged scheme, that bypasses Content Security Policy:注册绕过内容安全策略的特权方案的示例:
const { protocol } = require('electron')
protocol.registerSchemesAsPrivileged([
{ scheme: 'foo', privileges: { bypassCSP: true } }
])
A standard scheme adheres to what RFC 3986 calls generic URI syntax. 标准方案遵循RFC 3986所称的通用URI语法。For example 例如,http
and https
are standard schemes, while file
is not.http
和https
是标准方案,而file
则不是。
Registering a scheme as standard allows relative and absolute resources to be resolved correctly when served. 将方案注册为标准可以在提供服务时正确解析相对资源和绝对资源。Otherwise the scheme will behave like the 否则,该方案的行为将类似于文件协议,但没有解析相对URL的能力。file
protocol, but without the ability to resolve relative URLs.
For example when you load following page with custom protocol without registering it as standard scheme, the image will not be loaded because non-standard schemes can not recognize relative URLs:例如,当您使用自定义协议加载以下页面而未将其注册为标准方案时,将不会加载图像,因为非标准方案无法识别相对URL:
<body>
<img src='test.png'>
</body>
Registering a scheme as standard will allow access to files through the FileSystem API. 将方案注册为标准将允许通过FileSystem API访问文件。Otherwise the renderer will throw a security error for the scheme.否则,呈现器将抛出该方案的安全错误。
By default web storage apis (localStorage, sessionStorage, webSQL, indexedDB, cookies) are disabled for non standard schemes. 默认情况下,非标准方案禁用web存储api(localStorage、sessionStorage、webSQL、indexedDB、cookie)。So in general if you want to register a custom protocol to replace the 因此,通常情况下,如果您想注册一个自定义协议来取代http
protocol, you have to register it as a standard scheme.http
协议,则必须将其注册为标准方案。
Protocols that use streams (http and stream protocols) should set 使用流的协议(http和流协议)应该设置stream: true
. stream: true
。The <video>
and <audio>
HTML elements expect protocols to buffer their responses by default. <video>
和<audio>
HTML元素期望协议在默认情况下缓冲它们的响应。The 流标志将这些元素配置为正确预期流响应。stream
flag configures those elements to correctly expect streaming responses.
protocol.registerFileProtocol(scheme, handler)
scheme
stringhandler
Functionrequest
ProtocolRequestcallback
Functionresponse
(string | ProtocolResponse)
Returns 返回boolean
- Whether the protocol was successfully registered协议是否已成功注册
Registers a protocol of 注册一个scheme
that will send a file as the response. scheme
的协议,该协议将发送一个文件作为响应。The handler
will be called with request
and callback
where request
is an incoming request for the scheme
.handler
将使用request
和callback
进行调用,其中request
是scheme
的传入请求。
To handle the 要处理request
, the callback
should be called with either the file's path or an object that has a path
property, e.g. callback(filePath)
or callback({ path: filePath })
. request
,callback
应该使用文件的path
或具有路径属性的对象来调用,例如callback(filePath)
或callback({ path: filePath })
。The filePath
must be an absolute path.filePath
必须是绝对路径。
By default the 默认情况下,该scheme
is treated like http:
, which is parsed differently from protocols that follow the "generic URI syntax" like file:
.scheme
被视为http:
,其解析方式与遵循“通用URI语法”(如file:
)的协议不同。
protocol.registerBufferProtocol(scheme, handler)
scheme
stringhandler
Functionrequest
ProtocolRequestcallback
Functionresponse
(Buffer | ProtocolResponse)
Returns 返回boolean
- Whether the protocol was successfully registered协议是否已成功注册
Registers a protocol of 注册将发送scheme
that will send a Buffer
as a response.Buffer
作为响应的scheme
的协议。
The usage is the same with 用法与registerFileProtocol
, except that the callback
should be called with either a Buffer
object or an object that has the data
property.registerFileProtocol
相同,只是callback
应使用Buffer
对象或具有data
属性的对象调用。
Example:示例
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)
Returns 返回boolean
- Whether the protocol was successfully registered协议是否已成功注册
Registers a protocol of 注册将发送scheme
that will send a string
as a response.string
作为响应的scheme
的协议。
The usage is the same with 用法与registerFileProtocol
, except that the callback
should be called with either a string
or an object that has the data
property.registerFileProtocol
相同,只是callback
应该使用string
或具有data
属性的对象进行调用。
protocol.registerHttpProtocol(scheme, handler)
scheme
stringhandler
Functionrequest
ProtocolRequestcallback
Functionresponse
ProtocolResponse
Returns 返回boolean
- Whether the protocol was successfully registered协议是否已成功注册
Registers a protocol of 注册将发送HTTP请求作为响应的scheme
that will send an HTTP request as a response.scheme
的协议。
The usage is the same with 用法与registerFileProtocol
, except that the callback
should be called with an object that has the url
property.registerFileProtocol
相同,只是callback
应该使用具有url
属性的对象进行调用。
protocol.registerStreamProtocol(scheme, handler)
scheme
stringhandler
Functionrequest
ProtocolRequestcallback
Functionresponse
(ReadableStream | ProtocolResponse)
Returns 返回boolean
- Whether the protocol was successfully registered协议是否已成功注册
Registers a protocol of 注册将发送流作为响应的scheme
that will send a stream as a response.scheme
的协议。
The usage is the same with 其用法与registerFileProtocol
, except that the callback
should be called with either a ReadableStream object or an object that has the data
property.registerFileProtocol
相同,只是callback
应使用ReadableStream对象或具有数据属性的对象进行调用。
Example:示例:
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>')
})
})
It is possible to pass any object that implements the readable stream API (emits 可以传递任何实现可读流API的对象(发出data
/end
/error
events). data
/end
/error
事件)。For example, here's how a file could be returned:例如,以下是如何返回文件:
protocol.registerStreamProtocol('atom', (request, callback) => {
callback(fs.createReadStream('index.html'))
})
protocol.unregisterProtocol(scheme)
scheme
string
Returns 返回boolean
- Whether the protocol was successfully unregistered协议是否已成功注销
Unregisters the custom protocol of 注销scheme
.scheme
的自定义协议。
protocol.isProtocolRegistered(scheme)
scheme
string
Returns 返回boolean
- Whether scheme
is already registered.scheme
是否已注册。
protocol.interceptFileProtocol(scheme, handler)
scheme
stringhandler
Functionrequest
ProtocolRequestcallback
Functionresponse
(string | ProtocolResponse)
Returns 返回boolean
- Whether the protocol was successfully intercepted协议是否被成功拦截
Intercepts 拦截scheme
protocol and uses handler
as the protocol's new handler which sends a file as a response.scheme
协议,并使用handler
作为协议的新处理程序,该处理程序将文件作为响应发送。
protocol.interceptStringProtocol(scheme, handler)
scheme
stringhandler
Functionrequest
ProtocolRequestcallback
Functionresponse
(string | ProtocolResponse)
Returns 返回boolean
- Whether the protocol was successfully intercepted协议是否被成功拦截
Intercepts 拦截scheme
protocol and uses handler
as the protocol's new handler which sends a string
as a response.scheme
协议,并使用handler
作为协议的新处理程序,该处理程序发送string
作为响应。
protocol.interceptBufferProtocol(scheme, handler)
scheme
stringhandler
Functionrequest
ProtocolRequestcallback
Functionresponse
(Buffer | ProtocolResponse)
Returns 返回boolean
- Whether the protocol was successfully intercepted协议是否被成功拦截
Intercepts 拦截scheme
protocol and uses handler
as the protocol's new handler which sends a Buffer
as a response.scheme
协议,并使用handler
作为协议的新处理程序,该处理程序发送Buffer
作为响应。
protocol.interceptHttpProtocol(scheme, handler)
scheme
stringhandler
Functionrequest
ProtocolRequestcallback
Functionresponse
ProtocolResponse
Returns 返回boolean
- Whether the protocol was successfully intercepted协议是否被成功拦截
Intercepts 拦截scheme
protocol and uses handler
as the protocol's new handler which sends a new HTTP request as a response.scheme
协议并使用handler
作为协议的新处理程序,该处理程序发送新的HTTP请求作为响应。
protocol.interceptStreamProtocol(scheme, handler)
scheme
stringhandler
Functionrequest
ProtocolRequestcallback
Functionresponse
(ReadableStream | ProtocolResponse)
Returns 返回boolean
- Whether the protocol was successfully intercepted协议是否被成功拦截
Same as 与protocol.registerStreamProtocol
, except that it replaces an existing protocol handler.protocol.registerStreamProtocol
相同,只是它替换了现有的协议处理程序。
protocol.uninterceptProtocol(scheme)
scheme
string
Returns 返回boolean
- Whether the protocol was successfully unintercepted协议是否成功未被察觉
Remove the interceptor installed for 删除为scheme
and restore its original handler.scheme
安装的拦截器并恢复其原始处理程序。
protocol.isProtocolIntercepted(scheme)
scheme
string
Returns 返回boolean
- Whether scheme
is already intercepted.scheme
是否已被拦截。