* feat: add protocol.registerSource()
A protocol.handle() handler runs on the main thread, so requests to an
app's own scheme wait whenever the main process is busy there, most
visibly at startup when the first window's HTML, scripts and styles are
served by that handler. For the common case of serving bundled files
there is nothing for JavaScript to decide, so let the app declare it:
protocol.registerSource('app', {
routes: [
{ match: { host: 'bundle', path: '/assets/' },
source: { type: 'directory', root: assetsDir } },
{ match: { host: 'bundle' },
source: { type: 'directory', root: distDir } }
]
})
The routes are compiled into an immutable ProtocolSource held by the
session's ProtocolRegistry. The URLLoaderFactory the registry hands out
for the scheme (to renderers for subresources, to navigations, and to
net.fetch through ProtocolRegistry::CreateRegisteredFactory) is bound on
the IO thread; it picks the most specific route (a host match over a
wildcard, then the longest path prefix), resolves the rest of the path
inside that route's root, refusing anything that would leave it, and
hands the file to AsarURLLoader, which reads it on a blocking sequence
the way file: URLs are read, asar archives included, with Content-Type
from the extension and any headers the route adds. AsarURLLoader reads
plain files itself for this (read_plain_files) rather than delegating to
Chromium's file loader, whose Last-Modified formatting costs more than
the read for small files. A scheme has either a handler or a source;
unhandle() removes either and isProtocolHandled() reports both.
Linux x64, page with 60 stylesheets, median of 3 warm loads:
protocol.handle on the main thread 22 ms idle / 120 ms with the main
process busy for 100 ms after navigation; registerSource 13 ms / 14 ms.
Renderer fetch() round trip 0.33 -> 0.20 ms; browser-process CPU per
request 234 -> 200 us with no main-thread time at all.
* test: protocol.registerSource
* fix: address review of protocol.registerSource
- HEAD requests get the response head with Content-Type/Content-Length
and an empty body, without opening or reading the file.
- A satisfiable Range is answered 206 with Content-Range and
Content-Length; an unsatisfiable one 416 with `bytes */size`.
- Route roots are canonicalized at registration and each requested file
is resolved (symlinks included) before it is opened; a file that is not
under the root is not served.
- Plain-file sizes no longer pass through Archive::FileInfo's 32-bit
size, so files over 4 GiB are served whole.
- registerSource rejects the full set of built-in schemes
(ProtocolRegistry::IsBuiltinScheme), not just the legacy list.
- Reduce a few variable scopes, drop Route's out-of-line special members.
* fix: address second review of protocol.registerSource
* chore: oxfmt
* docs: mark protocol.registerSource() and getSource() as experimental
* fix: tighten registerSource() route validation and root containment
* docs: note that loader-computed headers override route headers
22 KiB
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:
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())
})
})
Note
All methods unless specified can only be used after the
readyevent of theappmodule 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 { app, BrowserWindow, net, protocol, session } = require('electron')
const path = require('node:path')
const url = require('node: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 names
RFC 3986 defines what a valid protocol name is:
Scheme names consist of a sequence of characters beginning with a letter and followed by any combination of letters, digits, plus ("+"), period ("."), or hyphen ("-"). Although schemes are case-insensitive, the canonical form is lowercase […].
Methods
The protocol module has the following methods:
protocol.registerSchemesAsPrivileged(customSchemes)
customSchemesCustomScheme[]
Note
This method can only be used before the
readyevent of theappmodule 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, streaming
video/audio, and V8 code cache. Specify a privilege with the value of true to
enable the capability.
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.
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:
<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.
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)
schemestring - scheme to handle, for examplehttpsormy-app. This is the bit before the:in a URL.handlerFunction<GlobalResponse | Promise<GlobalResponse>>requestGlobalRequest
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.
In addition to the standard Request fields, request.initiatorOrigin is set to the
origin that issued the request (for example https://example.com, or null
for an opaque origin) when web content made it; it is absent for requests the
browser started itself. Unlike request.referrer it is not controlled by the
requesting page, so prefer it when deciding whether to serve a request.
Either a Response or a Promise<Response> can be returned.
Example:
const { app, net, protocol } = require('electron')
const path = require('node:path')
const { pathToFileURL } = require('node: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
})
}
})
})
See the MDN docs for Request and Response for more details.
protocol.unhandle(scheme)
schemestring - scheme for which to remove the handler.
Removes a protocol handler registered with protocol.handle or a source
registered with protocol.registerSource.
protocol.registerSource(scheme, source) Experimental
schemestring - a custom scheme registered withprotocol.registerSchemesAsPrivileged.sourceProtocolSource
Serves scheme from directories on disk without a JavaScript handler. Each
request is matched against routes (a route with a host wins over one
without, then the longest path prefix wins), the rest of the URL's path is
resolved inside that route's root, and the file is streamed to the requester
the way file: URLs are, including from asar archives, with Content-Type
taken from the file extension. A path that resolves outside root, a missing
file, a request that matches no route, or a method other than GET/HEAD
fails with net::ERR_FILE_NOT_FOUND. A URL whose path ends in / serves the
route's index file.
Use this instead of protocol.handle when a scheme only serves an app's own
bundled files: no request touches the main thread, so pages and their
subresources load at the same speed whether or not the main process is busy.
const { app, protocol } = require('electron')
const path = require('node:path')
protocol.registerSchemesAsPrivileged([
{ scheme: 'app', privileges: { standard: true, secure: true, supportFetchAPI: true } }
])
app.whenReady().then(() => {
protocol.registerSource('app', {
routes: [
{
match: { host: 'bundle', path: '/assets/' },
source: { type: 'directory', root: path.join(process.resourcesPath, 'assets') }
},
{
match: { host: 'bundle' },
source: {
type: 'directory',
root: path.join(app.getAppPath(), 'dist'),
headers: { 'Cross-Origin-Opener-Policy': 'same-origin' }
}
}
]
})
})
A scheme has either a handler or a source; protocol.unhandle removes either,
and protocol.isProtocolHandled reports both. webRequest listeners apply to
these requests as to any other.
protocol.getSource(scheme) Experimental
schemestring
Returns ProtocolSource | null - The source
registered for scheme with protocol.registerSource, or null.
protocol.isProtocolHandled(scheme)
schemestring
Returns boolean - Whether scheme already has a handler or a source.
protocol.registerFileProtocol(scheme, handler) Deprecated
schemestringhandlerFunctionrequestProtocolRequestcallbackFunctionresponse(string | ProtocolResponse)
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
schemestringhandlerFunctionrequestProtocolRequestcallbackFunctionresponse(Buffer | ProtocolResponse)
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:
protocol.registerBufferProtocol('atom', (request, callback) => {
callback({ mimeType: 'text/html', data: Buffer.from('<h5>Response</h5>') })
})
protocol.registerStringProtocol(scheme, handler) Deprecated
schemestringhandlerFunctionrequestProtocolRequestcallbackFunctionresponse(string | ProtocolResponse)
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
schemestringhandlerFunctionrequestProtocolRequestcallbackFunctionresponseProtocolResponse
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
schemestringhandlerFunctionrequestProtocolRequestcallbackFunctionresponse(ReadableStream | ProtocolResponse)
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:
const { protocol } = require('electron')
const { PassThrough } = require('node: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). For example, here's how a file could be returned:
protocol.registerStreamProtocol('atom', (request, callback) => {
callback(fs.createReadStream('index.html'))
})
protocol.unregisterProtocol(scheme) Deprecated
schemestring
Returns boolean - Whether the protocol was successfully unregistered
Unregisters the custom protocol of scheme.
protocol.isProtocolRegistered(scheme) Deprecated
schemestring
Returns boolean - Whether scheme is already registered.
protocol.interceptFileProtocol(scheme, handler) Deprecated
schemestringhandlerFunctionrequestProtocolRequestcallbackFunctionresponse(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.
protocol.interceptStringProtocol(scheme, handler) Deprecated
schemestringhandlerFunctionrequestProtocolRequestcallbackFunctionresponse(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.
protocol.interceptBufferProtocol(scheme, handler) Deprecated
schemestringhandlerFunctionrequestProtocolRequestcallbackFunctionresponse(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.
protocol.interceptHttpProtocol(scheme, handler) Deprecated
schemestringhandlerFunctionrequestProtocolRequestcallbackFunctionresponseProtocolResponse
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
schemestringhandlerFunctionrequestProtocolRequestcallbackFunctionresponse(ReadableStream | ProtocolResponse)
Returns boolean - Whether the protocol was successfully intercepted
Same as protocol.registerStreamProtocol, except that it replaces an existing
protocol handler.
protocol.uninterceptProtocol(scheme) Deprecated
schemestring
Returns boolean - Whether the protocol was successfully unintercepted
Remove the interceptor installed for scheme and restore its original handler.
protocol.isProtocolIntercepted(scheme) Deprecated
schemestring
Returns boolean - Whether scheme is already intercepted.