Skip to main content

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 sessionprotocol与自定义partitionsession一起使用

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.但是,如果您在browserWindowwebPreferences上定义了一个partitionsession,那么该窗口将使用不同的会话,如果您只使用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)

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.例如,httphttps是标准方案,而file则不是。

Registering a scheme as standard allows relative and absolute resources to be resolved correctly when served. 将方案注册为标准可以在提供服务时正确解析相对资源和绝对资源。Otherwise the scheme will behave like the file protocol, but without the ability to resolve relative URLs.否则,该方案的行为将类似于文件协议,但没有解析相对URL的能力。

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 stream: true. 使用流的协议(http和流协议)应该设置stream: trueThe <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)

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将使用requestcallback进行调用,其中requestscheme的传入请求。

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 }). 要处理requestcallback应该使用文件的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)

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)

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 string
  • handler Function

Returns 返回boolean - Whether the protocol was successfully registered协议是否已成功注册

Registers a protocol of scheme that will send an HTTP request as a response.注册将发送HTTP请求作为响应的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)

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 data/end/error events). 可以传递任何实现可读流API的对象(发出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)

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)

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)

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)

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)

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是否已被拦截。