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:

  1. const { app, protocol, net } = require('electron')
  2. app.whenReady().then(() => {
  3. protocol.handle('atom', (request) =>
  4. net.fetch('file://' + request.url.slice('atom://'.length)))
  5. })

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.

  1. const { app, BrowserWindow, net, protocol, session } = require('electron')
  2. const path = require('node:path')
  3. const url = require('url')
  4. app.whenReady().then(() => {
  5. const partition = 'persist:example'
  6. const ses = session.fromPartition(partition)
  7. ses.protocol.handle('atom', (request) => {
  8. const filePath = request.url.slice('atom://'.length)
  9. return net.fetch(url.pathToFileURL(path.join(__dirname, filePath)).toString())
  10. })
  11. const mainWindow = new BrowserWindow({ webPreferences: { partition } })
  12. })

Methods

The protocol module has the following methods:

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.

Registers the scheme as standard, secure, bypasses content security policy for resources, allows registering ServiceWorker, supports fetch API, and streaming video/audio. Specify a privilege with the value of true to enable the capability.

An example of registering a privileged scheme, that bypasses Content Security Policy:

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

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 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.

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:

  1. <body>
  2. <img src='test.png'>
  3. </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.

Protocols that use streams (http and stream protocols) should set stream: true. The <video> and <audio> HTML elements expect protocols to buffer their responses by default. The stream flag configures those elements to correctly expect streaming responses.

protocol.handle(scheme, handler)

  • scheme string - scheme to handle, for example https or my-app. This is the bit before the : in a URL.
  • handler Function<GlobalResponse | Promise<GlobalResponse>>

Register a protocol handler for scheme. Requests made to URLs with this scheme will delegate to this handler to determine what response should be sent.

Either a Response or a Promise<Response> can be returned.

Example:

  1. const { app, net, protocol } = require('electron')
  2. const { join } = require('node:path')
  3. const { pathToFileURL } = require('url')
  4. protocol.registerSchemesAsPrivileged([
  5. {
  6. scheme: 'app',
  7. privileges: {
  8. standard: true,
  9. secure: true,
  10. supportFetchAPI: true
  11. }
  12. }
  13. ])
  14. app.whenReady().then(() => {
  15. protocol.handle('app', (req) => {
  16. const { host, pathname } = new URL(req.url)
  17. if (host === 'bundle') {
  18. if (pathname === '/') {
  19. return new Response('<h1>hello, world</h1>', {
  20. headers: { 'content-type': 'text/html' }
  21. })
  22. }
  23. // NB, this does not check for paths that escape the bundle, e.g.
  24. // app://bundle/../../secret_file.txt
  25. return net.fetch(pathToFileURL(join(__dirname, pathname)).toString())
  26. } else if (host === 'api') {
  27. return net.fetch('https://api.my-server.com/' + pathname, {
  28. method: req.method,
  29. headers: req.headers,
  30. body: req.body
  31. })
  32. }
  33. })
  34. })

See the MDN docs for Request and Response for more details.

protocol.unhandle(scheme)

  • scheme string - scheme for which to remove the handler.

Removes a protocol handler registered with protocol.handle.

protocol.isProtocolHandled(scheme)

  • scheme string

Returns boolean - Whether scheme is already handled.

protocol.registerFileProtocol(scheme, handler) Deprecated

Returns boolean - Whether the protocol was successfully registered

Registers a protocol of scheme that will send a file as the response. The handler will be called with request and callback where request is an incoming request for the 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 }). The filePath must be an absolute path.

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

protocol.registerBufferProtocol(scheme, handler) Deprecated

Returns boolean - Whether the protocol was successfully registered

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 property.

Example:

  1. protocol.registerBufferProtocol('atom', (request, callback) => {
  2. callback({ mimeType: 'text/html', data: Buffer.from('<h5>Response</h5>') })
  3. })

protocol.registerStringProtocol(scheme, handler) Deprecated

Returns boolean - Whether the protocol was successfully registered

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 property.

protocol.registerHttpProtocol(scheme, handler) Deprecated

Returns boolean - Whether the protocol was successfully registered

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 an object that has the url property.

protocol.registerStreamProtocol(scheme, handler) Deprecated

Returns boolean - Whether the protocol was successfully registered

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

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.

Example:

  1. const { protocol } = require('electron')
  2. const { PassThrough } = require('stream')
  3. function createStream (text) {
  4. const rv = new PassThrough() // PassThrough is also a Readable stream
  5. rv.push(text)
  6. rv.push(null)
  7. return rv
  8. }
  9. protocol.registerStreamProtocol('atom', (request, callback) => {
  10. callback({
  11. statusCode: 200,
  12. headers: {
  13. 'content-type': 'text/html'
  14. },
  15. data: createStream('<h5>Response</h5>')
  16. })
  17. })

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:

  1. protocol.registerStreamProtocol('atom', (request, callback) => {
  2. callback(fs.createReadStream('index.html'))
  3. })

protocol.unregisterProtocol(scheme) Deprecated

  • scheme string

Returns boolean - Whether the protocol was successfully unregistered

Unregisters the custom protocol of scheme.

protocol.isProtocolRegistered(scheme) Deprecated

  • scheme string

Returns boolean - Whether scheme is already registered.

protocol.interceptFileProtocol(scheme, handler) Deprecated

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.

protocol.interceptStringProtocol(scheme, handler) Deprecated

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.

protocol.interceptBufferProtocol(scheme, handler) Deprecated

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.

protocol.interceptHttpProtocol(scheme, handler) Deprecated

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.

protocol.interceptStreamProtocol(scheme, handler) Deprecated

Returns boolean - Whether the protocol was successfully intercepted

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

protocol.uninterceptProtocol(scheme) Deprecated

  • scheme string

Returns boolean - Whether the protocol was successfully unintercepted

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

protocol.isProtocolIntercepted(scheme) Deprecated

  • scheme string

Returns boolean - Whether scheme is already intercepted.