目录
当前位置: 首页 > 文档资料 > Electron 中文文档 >

protocol

优质
小牛编辑
156浏览
2023-12-01

注册自定义协议并拦截基于现有协议的请求。

线程:主线程

实现与 file:// 协议具有相同效果的协议的示例:

const { app, protocol } = require('electron')
const path = require('path')
app.on('ready', () => {
  protocol.registerFileProtocol('atom', (request, callback) => {
    const url = request.url.substr(7)
    callback({ path: path.normalize(`${__dirname}/${url}`) })
  }, (error) => {
    if (error) console.error('Failed to register protocol')
  })
})

注意: 除了指定的方法, 其他方法只能在 app 模块的 ready 事件被触发后使用。

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:

const { app, protocol } = require('electron')
const path = require('path')
app.on('ready', () => {
  protocol.registerFileProtocol('atom', (request, callback) => {
    const url = request.url.substr(7)
    callback({ path: path.normalize(`${__dirname}/${url}`) })
  }, (error) => {
    if (error) console.error('Failed to register protocol')
  })
})

Note: All methods unless specified can only be used after the ready event of the app module gets emitted.

Using protocol with a custom partition or session

A protocol is registered to a specific Electron session object. If you don't specify a session, then your protocol will be applied to the default session that Electron uses. 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.

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.on('ready', () => {
  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}`) })
  }, (error) => {
    if (error) console.error('Failed to register protocol')
  })
  mainWindow = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {partition: partition
    }
  })
})

Using protocol with a custom partition or session

A protocol is registered to a specific Electron session object. If you don't specify a session, then your protocol will be applied to the default session that Electron uses. 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.

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.on('ready', () => {
  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}`) })
  }, (error) => {
    if (error) console.error('Failed to register protocol')
  })
  mainWindow = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {partition: partition
    }
  })
})

方法

protocol 模块具有以下方法:

Methods

The protocol module has the following methods:

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.

Registers the scheme as standard, secure, bypasses content security policy for resources, allows registering ServiceWorker and supports fetch API.

Specify a privilege with the value of true to enable the capability. An example of registering a privileged scheme, with bypassing Content Security Policy:

const { protocol } = require('electron')
protocol.registerSchemesAsPrivileged([
  { scheme: 'foo', privileges: { bypassCSP: true } }
])

标准scheme遵循 RFC 3986 所设定的 URI泛型语法 。 例如, httphttps 是标准协议, 而 file 不是。

将一个scheme注册为标准scheme, 将保证相对和绝对资源在使用时能够得到正确的解析。 否则, 该协议将表现为 file 协议, 而且,这种文件协议将不能解析相对路径。

例如, 当您使用自定义协议加载以下内容时,如果你不将其注册为标准scheme, 图片将不会被加载, 因为非标准scheme无法识别相对 路径:

<body>
  <img src='test.png'>
</body>

注册一个scheme作为标准scheme将允许其通过FileSystem 接口访问文件。 否则, 渲染器将会因为该scheme,而抛出一个安全性错误。

默认情况下web storage apis (localStorage, sessionStorage, webSQL, indexedDB, cookies) 被禁止访问非标准schemes。 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.

protocol.registerSchemesAsPrivileged can be used to replicate the functionality of the previous protocol.registerStandardSchemes, webFrame.registerURLSchemeAs* and protocol.registerServiceWorkerSchemes functions that existed prior to Electron 5.0.0, for example:

before (<= v4.x)

// Main
protocol.registerStandardSchemes(['scheme1', 'scheme2'], { secure: true })
// Renderer
webFrame.registerURLSchemeAsPrivileged('scheme1', { secure: true })
webFrame.registerURLSchemeAsPrivileged('scheme2', { secure: true })

after (>= v5.x)

protocol.registerSchemesAsPrivileged([
  { scheme: 'scheme1', privileges: { standard: true, secure: true } },
  { scheme: 'scheme2', privileges: { standard: true, secure: true } }
])

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.

Registers the scheme as standard, secure, bypasses content security policy for resources, allows registering ServiceWorker and supports fetch API.

Specify a privilege with the value of true to enable the capability. An example of registering a privileged scheme, with bypassing 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. For example http and https are standard schemes, while file is not.

Registering a scheme as standard, will allow 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.

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:

<body>
  <img src='test.png'>
</body>

Registering a scheme as standard will allow access to files through the 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. 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.

protocol.registerSchemesAsPrivileged can be used to replicate the functionality of the previous protocol.registerStandardSchemes, webFrame.registerURLSchemeAs* and protocol.registerServiceWorkerSchemes functions that existed prior to Electron 5.0.0, for example:

before (<= v4.x)

// Main
protocol.registerStandardSchemes(['scheme1', 'scheme2'], { secure: true })
// Renderer
webFrame.registerURLSchemeAsPrivileged('scheme1', { secure: true })
webFrame.registerURLSchemeAsPrivileged('scheme2', { secure: true })

after (>= v5.x)

protocol.registerSchemesAsPrivileged([
  { scheme: 'scheme1', privileges: { standard: true, secure: true } },
  { scheme: 'scheme2', privileges: { standard: true, secure: true } }
])

protocol.registerFileProtocol(scheme, handler[, completion])

  • scheme String
  • handler Function - 回调函数

    • request Object

      • url String
      • referrer String
      • method String
      • uploadData UploadData[]
    • callback Function

      • filePath String (可选)
  • completion Function (可选)

    • error Error

注册一个 scheme 协议, 将该文件作为响应发送 当要使用 scheme 创建 request 时, 将使用 handler(request, callback) 来调用 handlercompletion 将在 scheme 注册成功时通过completion(null) 调用,失败时通过completion(error) 调用。

要处理 request, 应当使用文件的路径或具有 path 属性的对象来调用 callback。例如:callback(filePath)callback({ path: filePath }). The object may also have a headers property which gives a map of headers to values for the response headers, e.g. callback({ path: filePath, headers: {"Content-Security-Policy": "default-src 'none'"]}).

callback 被调用后,并且没有带着数字或 error 属性的对象时, request将会失败, 并且带有你指定的 error错误号。 更多的错误号信息,您可以查阅网络错误列表.

By default the scheme is treated like http:, which is parsed differently than protocols that follow the "generic URI syntax" like file:.

protocol.registerFileProtocol(scheme, handler[, completion])

  • scheme String
  • handler Function

    • request Object

      • url String
      • referrer String
      • method String
      • uploadData UploadData[]
    • callback Function

      • filePath String (optional)
  • completion Function (optional)

    • error Error

Registers a protocol of scheme that will send the file as a response. The handler will be called with handler(request, callback) when a request is going to be created with scheme. completion will be called with completion(null) when scheme is successfully registered or completion(error) when failed.

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 }). The object may also have a headers property which gives a map of headers to values for the response headers, e.g. callback({ path: filePath, headers: {"Content-Security-Policy": "default-src 'none'"]}).

When callback is called with nothing, a number, or an object that has an error property, the request will fail with the error number you specified. For the available error numbers you can use, please see the net error list.

By default the scheme is treated like http:, which is parsed differently than protocols that follow the "generic URI syntax" like file:.

protocol.registerBufferProtocol(scheme, handler[, completion])

  • scheme String
  • handler Function - 回调函数

    • request Object

      • url String
      • referrer String
      • method String
      • uploadData UploadData[]
    • callback Function - 回调函数

      • buffer (Buffer | MimeTypedBuffer) (可选)
  • completion Function (可选)

    • error Error

注册一个 scheme 协议, 将 Buffer作为响应发送

该用法与 registerFileProtocol 相同, 只是callback 会被Buffer对象或者带有datamimeTypecharset属性的对象调用。

示例:

const { protocol } = require('electron')
protocol.registerBufferProtocol('atom', (request, callback) => {
  callback({ mimeType: 'text/html', data: Buffer.from('<h5>Response</h5>') })
}, (error) => {
  if (error) console.error('Failed to register protocol')
})

protocol.registerBufferProtocol(scheme, handler[, completion])

  • scheme String
  • handler Function

    • request Object

      • url String
      • referrer String
      • method String
      • uploadData UploadData[]
    • callback Function

      • buffer (Buffer | MimeTypedBuffer) (optional)
  • completion Function (optional)

    • error Error

Registers a protocol of scheme that will send a Buffer as a response.

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, mimeType, and charset properties.

Example:

const { protocol } = require('electron')
protocol.registerBufferProtocol('atom', (request, callback) => {
  callback({ mimeType: 'text/html', data: Buffer.from('<h5>Response</h5>') })
}, (error) => {
  if (error) console.error('Failed to register protocol')
})

protocol.registerStringProtocol(scheme, handler[, completion])

  • scheme String
  • handler Function - 回调函数

    • request Object

      • url String
      • referrer String
      • method String
      • uploadData UploadData[]
    • callback Function - 回调函数

      • data String (可选)
  • completion Function (可选)

    • error Error

注册一个 scheme 协议, 将 String 作为响应发送

该用法与 registerFileProtocol 相同, 只是callback 会被String对象或者带有datamimeTypecharset属性的对象调用。

protocol.registerStringProtocol(scheme, handler[, completion])

  • scheme String
  • handler Function

    • request Object

      • url String
      • referrer String
      • method String
      • uploadData UploadData[]
    • callback Function

      • data String (optional)
  • completion Function (optional)

    • error Error

Registers a protocol of scheme that will send a String as a response.

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, mimeType, and charset properties.

protocol.registerHttpProtocol(scheme, handler[, completion])

  • scheme String
  • handler Function - 回调函数

    • request Object

      • url String
      • headers Object
      • referrer String
      • method String
      • uploadData UploadData[]
    • callback Function - 回调函数

      • redirectRequest Object

        • url String
        • method String
        • session Object (可选)
        • uploadData Object (可选)

          • contentType String - 内容的MIME类型。
          • data String - 要发送的内容。
  • completion Function (可选)

    • error Error

注册一个 scheme 协议, 将 HTTP 请求作为响应发送

该用法与 registerFileProtocol 相同, 只是callback 会被redirectRequest对象或者带有url, method, referrer, uploadDatasession 属性的对象调用。

默认情况下, HTTP 请求会重复使用当前的 session。如果希望请求具有不同的session, 则应将 session设置为 null.

对于 POST 请求, 必须提供 uploadData 对象。

protocol.registerHttpProtocol(scheme, handler[, completion])

  • scheme String
  • handler Function

    • request Object

      • url String
      • headers Object
      • referrer String
      • method String
      • uploadData UploadData[]
    • callback Function

      • redirectRequest Object

        • url String
        • method String
        • session Object (optional)
        • uploadData Object (optional)

          • contentType String - MIME type of the content.
          • data String - Content to be sent.
  • completion Function (optional)

    • error Error

Registers a protocol of scheme that will send an HTTP request as a response.

The usage is the same with registerFileProtocol, except that the callback should be called with a redirectRequest object that has the url, method, referrer, uploadData and session properties.

By default the HTTP request will reuse the current session. If you want the request to have a different session you should set session to null.

For POST requests the uploadData object must be provided.

protocol.registerStreamProtocol(scheme, handler[, completion])

  • scheme String
  • handler Function - 回调函数

    • request Object

      • url String
      • headers Object
      • referrer String
      • method String
      • uploadData UploadData[]
    • callback Function - 回调函数

      • stream(ReadableStream | StreamProtocolResponse ) (可选)
  • completion Function (可选)

    • error Error

注册一个 scheme 协议, 将 Readable作为响应发送

该用法类似于 register{Any}Protocol ,只是callback 会被Readable对象或者带有data, statusCodeheaders 属性的对象调用。

示例:

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>')
  })
}, (error) => {
  if (error) console.error('Failed to register protocol')
})

可以传递任何可读取流 API 的对象(data/end/error 事件)。以下是如何返回文件的方法示例:

const { protocol } = require('electron')
const fs = require('fs')
protocol.registerStreamProtocol('atom', (request, callback) => {
  callback(fs.createReadStream('index.html'))
}, (error) => {
  if (error) console.error('Failed to register protocol')
})

protocol.registerStreamProtocol(scheme, handler[, completion])

  • scheme String
  • handler Function

    • request Object

      • url String
      • headers Object
      • referrer String
      • method String
      • uploadData UploadData[]
    • callback Function

      • stream (ReadableStream | StreamProtocolResponse) (optional)
  • completion Function (optional)

    • error Error

Registers a protocol of scheme that will send a Readable as a response.

The usage is similar to the other register{Any}Protocol, except that the callback should be called with either a Readable object or an object that has the data, statusCode, and headers properties.

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>')
  })
}, (error) => {
  if (error) console.error('Failed to register protocol')
})

It is possible to pass any object that implements the readable stream API (emits data/end/error events). For example, here's how a file could be returned:

const { protocol } = require('electron')
const fs = require('fs')
protocol.registerStreamProtocol('atom', (request, callback) => {
  callback(fs.createReadStream('index.html'))
}, (error) => {
  if (error) console.error('Failed to register protocol')
})

protocol.unregisterProtocol(scheme[, completion])

  • scheme String
  • completion Function (可选)

    • error Error

取消对自定义scheme的注册

protocol.unregisterProtocol(scheme[, completion])

  • scheme String
  • completion Function (optional)

    • error Error

Unregisters the custom protocol of scheme.

protocol.isProtocolHandled(scheme, callback)

  • scheme String
  • callback Function

    • handled Boolean

callback 会被调用,带有布尔值,表示是否已经有scheme 的处理程序。

即将弃用

protocol.isProtocolHandled(scheme, callback)

  • scheme String
  • callback Function

    • handled Boolean

The callback will be called with a boolean that indicates whether there is already a handler for scheme.

Deprecated Soon

protocol.isProtocolHandled(scheme)

  • scheme String

Returns Promise<Boolean> - fulfilled with a boolean that indicates whether there is already a handler for scheme.

protocol.isProtocolHandled(scheme)

  • scheme String

Returns Promise<Boolean> - fulfilled with a boolean that indicates whether there is already a handler for scheme.

protocol.interceptFileProtocol(scheme, handler[, completion])

  • scheme String
  • handler Function - 回调函数

    • request Object

      • url String
      • referrer String
      • method String
      • uploadData UploadData[]
    • callback Function - 回调函数

      • filePath String
  • completion Function (可选)

    • error Error

终止 scheme 协议, 并将 handler 作为该protocol新的处理方式,即返回一个file。

protocol.interceptFileProtocol(scheme, handler[, completion])

  • scheme String
  • handler Function

    • request Object

      • url String
      • referrer String
      • method String
      • uploadData UploadData[]
    • callback Function

      • filePath String
  • completion Function (optional)

    • error Error

Intercepts scheme protocol and uses handler as the protocol's new handler which sends a file as a response.

protocol.interceptStringProtocol(scheme, handler[, completion])

  • scheme String
  • handler Function - 回调函数

    • request Object

      • url String
      • referrer String
      • method String
      • uploadData UploadData[]
    • callback Function - 回调函数

      • data String (可选)
  • completion Function (可选)

    • error Error

终止 scheme 协议, 并将 handler 作为该protocol新的处理方式,即返回一个String

protocol.interceptStringProtocol(scheme, handler[, completion])

  • scheme String
  • handler Function

    • request Object

      • url String
      • referrer String
      • method String
      • uploadData UploadData[]
    • callback Function

      • data String (optional)
  • completion Function (optional)

    • error Error

Intercepts scheme protocol and uses handler as the protocol's new handler which sends a String as a response.

protocol.interceptBufferProtocol(scheme, handler[, completion])

  • scheme String
  • handler Function - 回调函数

    • request Object

      • url String
      • referrer String
      • method String
      • uploadData UploadData[]
    • callback Function - 回调函数

      • buffer Buffer (可选)
  • completion Function (可选)

    • error Error

终止 scheme 协议, 并将 handler 作为该protocol新的处理方式,即返回一个Buffer

protocol.interceptBufferProtocol(scheme, handler[, completion])

  • scheme String
  • handler Function

    • request Object

      • url String
      • referrer String
      • method String
      • uploadData UploadData[]
    • callback Function

      • buffer Buffer (optional)
  • completion Function (optional)

    • error Error

Intercepts scheme protocol and uses handler as the protocol's new handler which sends a Buffer as a response.

protocol.interceptHttpProtocol(scheme, handler[, completion])

  • scheme String
  • handler Function

    • request Object

      • url String
      • headers Object
      • referrer String
      • method String
      • uploadData UploadData[]
    • callback Function

      • redirectRequest Object

        • url String
        • method String
        • session Object (可选)
        • uploadData Object (可选)

          • contentType String - 内容的MIME类型。
          • data String - 发送内容。
  • completion Function (可选)

    • error Error

终止 scheme 协议, 并将 handler 作为该protocol新的处理方式,即返回一个新 HTTP 请求。

protocol.interceptHttpProtocol(scheme, handler[, completion])

  • scheme String
  • handler Function

    • request Object

      • url String
      • headers Object
      • referrer String
      • method String
      • uploadData UploadData[]
    • callback Function

      • redirectRequest Object

        • url String
        • method String
        • session Object (optional)
        • uploadData Object (optional)

          • contentType String - MIME type of the content.
          • data String - Content to be sent.
  • completion Function (optional)

    • error Error

Intercepts scheme protocol and uses handler as the protocol's new handler which sends a new HTTP request as a response.

protocol.interceptStreamProtocol(scheme, handler[, completion])

  • scheme String
  • handler Function

    • request Object

      • url String
      • headers Object
      • referrer String
      • method String
      • uploadData UploadData[]
    • callback Function

      • stream(ReadableStream | StreamProtocolResponse ) (可选)
  • completion Function (可选)

    • error Error

它与 registerStreamProtocol方法相同, 不过它是用来替换现有的protocol处理方式。

protocol.interceptStreamProtocol(scheme, handler[, completion])

  • scheme String
  • handler Function

    • request Object

      • url String
      • headers Object
      • referrer String
      • method String
      • uploadData UploadData[]
    • callback Function

      • stream (ReadableStream | StreamProtocolResponse) (optional)
  • completion Function (optional)

    • error Error

Same as protocol.registerStreamProtocol, except that it replaces an existing protocol handler.

protocol.uninterceptProtocol(scheme[, completion])

  • scheme String
  • completion Function (可选)

    • error Error

移除为 scheme 安装的拦截器,并还原其原始处理方式。

protocol.uninterceptProtocol(scheme[, completion])

  • scheme String
  • completion Function (optional)

    • error Error

Remove the interceptor installed for scheme and restore its original handler.