electron/docs/api/protocol.md

330 lines
10 KiB
Markdown
Raw Normal View History

2013-09-09 07:35:57 +00:00
# protocol
2013-09-03 10:22:40 +00:00
> Register a custom protocol and intercept existing protocol requests.
2013-09-03 10:22:40 +00:00
2016-11-23 19:20:56 +00:00
Process: [Main](../glossary.md#main-process)
2016-11-03 17:26:00 +00:00
2015-08-29 05:03:39 +00:00
An example of implementing a protocol that has the same effect as the
2013-09-03 10:22:40 +00:00
`file://` protocol:
```javascript
2018-09-13 16:10:51 +00:00
const { app, protocol } = require('electron')
const path = require('path')
app.whenReady().then(() => {
protocol.registerFileProtocol('atom', (request, callback) => {
const url = request.url.substr(7)
2018-09-13 16:10:51 +00:00
callback({ path: path.normalize(`${__dirname}/${url}`) })
})
})
2013-09-03 10:22:40 +00:00
```
**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`](./session.md)
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.
```javascript
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 } })
})
```
2015-08-29 05:03:39 +00:00
## Methods
The `protocol` module has the following methods:
### `protocol.registerSchemesAsPrivileged(customSchemes)`
* `customSchemes` [CustomScheme[]](structures/custom-scheme.md)
**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:
```javascript
const { protocol } = require('electron')
protocol.registerSchemesAsPrivileged([
{ scheme: 'foo', privileges: { bypassCSP: true } }
])
```
A standard scheme adheres to what RFC 3986 calls [generic URI
syntax](https://tools.ietf.org/html/rfc3986#section-3). 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:
```html
<body>
<img src='test.png'>
</body>
```
2016-08-24 16:03:44 +00:00
Registering a scheme as standard will allow access to files through the
[FileSystem API][file-system-api]. Otherwise the renderer will throw a security
2016-09-21 18:50:34 +00:00
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.
2019-02-12 18:49:47 +00:00
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.registerFileProtocol(scheme, handler)`
2013-09-03 10:22:40 +00:00
* `scheme` String
* `handler` Function
* `request` ProtocolRequest
2016-10-13 06:30:57 +00:00
* `callback` Function
* `response` (String | [ProtocolResponse](structures/protocol-response.md))
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`.
2013-09-03 10:22:40 +00:00
2015-08-29 05:03:39 +00:00
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.
2013-09-03 10:22:40 +00:00
2015-08-29 05:03:39 +00:00
By default the `scheme` is treated like `http:`, which is parsed differently
from protocols that follow the "generic URI syntax" like `file:`.
2015-07-16 13:32:09 +00:00
### `protocol.registerBufferProtocol(scheme, handler)`
2013-09-03 10:22:40 +00:00
* `scheme` String
* `handler` Function
* `request` ProtocolRequest
2016-10-13 06:30:57 +00:00
* `callback` Function
* `response` (Buffer | [ProtocolResponse](structures/protocol-response.md))
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:
2015-07-16 13:32:09 +00:00
```javascript
protocol.registerBufferProtocol('atom', (request, callback) => {
2018-09-13 16:10:51 +00:00
callback({ mimeType: 'text/html', data: Buffer.from('<h5>Response</h5>') })
})
```
### `protocol.registerStringProtocol(scheme, handler)`
2013-09-03 10:22:40 +00:00
* `scheme` String
* `handler` Function
* `request` ProtocolRequest
2016-10-13 06:30:57 +00:00
* `callback` Function
* `response` (String | [ProtocolResponse](structures/protocol-response.md))
Returns `Boolean` - Whether the protocol was successfully registered
2013-09-03 10:22:40 +00:00
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.
2013-09-03 10:22:40 +00:00
### `protocol.registerHttpProtocol(scheme, handler)`
2013-09-03 10:22:40 +00:00
* `scheme` String
* `handler` Function
* `request` ProtocolRequest
2016-10-13 06:30:57 +00:00
* `callback` Function
* `response` ProtocolResponse
Returns `Boolean` - Whether the protocol was successfully registered
2015-08-29 05:03:39 +00:00
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)`
* `scheme` String
* `handler` Function
* `request` ProtocolRequest
* `callback` Function
* `response` (ReadableStream | [ProtocolResponse](structures/protocol-response.md))
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`](https://nodejs.org/api/stream.html#stream_class_stream_readable) object or an object that
has the `data` property.
Example:
```javascript
2018-09-13 16:10:51 +00:00
const { protocol } = require('electron')
const { PassThrough } = require('stream')
function createStream (text) {
2017-11-29 10:58:24 +00:00
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:
```javascript
protocol.registerStreamProtocol('atom', (request, callback) => {
callback(fs.createReadStream('index.html'))
})
```
### `protocol.unregisterProtocol(scheme)`
2013-09-03 10:22:40 +00:00
* `scheme` String
Returns `Boolean` - Whether the protocol was successfully unregistered
2013-09-03 10:22:40 +00:00
Unregisters the custom protocol of `scheme`.
2013-09-03 10:22:40 +00:00
### `protocol.isProtocolRegistered(scheme)`
* `scheme` String
Returns `Boolean` - Whether `scheme` is already registered.
### `protocol.interceptFileProtocol(scheme, handler)`
2013-09-03 10:22:40 +00:00
* `scheme` String
* `handler` Function
* `request` ProtocolRequest
2016-10-13 06:30:57 +00:00
* `callback` Function
* `response` (String | [ProtocolResponse](structures/protocol-response.md))
Returns `Boolean` - Whether the protocol was successfully intercepted
2013-09-03 10:22:40 +00:00
2015-08-29 05:03:39 +00:00
Intercepts `scheme` protocol and uses `handler` as the protocol's new handler
which sends a file as a response.
2015-03-16 12:53:45 +00:00
### `protocol.interceptStringProtocol(scheme, handler)`
2015-03-16 12:53:45 +00:00
* `scheme` String
* `handler` Function
* `request` ProtocolRequest
2016-10-13 06:30:57 +00:00
* `callback` Function
* `response` (String | [ProtocolResponse](structures/protocol-response.md))
Returns `Boolean` - Whether the protocol was successfully intercepted
2015-08-29 05:03:39 +00:00
Intercepts `scheme` protocol and uses `handler` as the protocol's new handler
which sends a `String` as a response.
2015-03-16 12:53:45 +00:00
### `protocol.interceptBufferProtocol(scheme, handler)`
* `scheme` String
* `handler` Function
* `request` ProtocolRequest
2016-10-13 06:30:57 +00:00
* `callback` Function
* `response` (Buffer | [ProtocolResponse](structures/protocol-response.md))
Returns `Boolean` - Whether the protocol was successfully intercepted
2015-06-17 03:32:39 +00:00
2015-08-29 05:03:39 +00:00
Intercepts `scheme` protocol and uses `handler` as the protocol's new handler
which sends a `Buffer` as a response.
2015-06-17 03:32:39 +00:00
### `protocol.interceptHttpProtocol(scheme, handler)`
2015-06-17 03:32:39 +00:00
* `scheme` String
* `handler` Function
* `request` ProtocolRequest
2016-10-13 06:30:57 +00:00
* `callback` Function
* `response` [ProtocolResponse](structures/protocol-response.md)
Returns `Boolean` - Whether the protocol was successfully intercepted
2015-08-29 05:03:39 +00:00
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)`
* `scheme` String
* `handler` Function
* `request` ProtocolRequest
* `callback` Function
* `response` (ReadableStream | [ProtocolResponse](structures/protocol-response.md))
Returns `Boolean` - Whether the protocol was successfully intercepted
Same as `protocol.registerStreamProtocol`, except that it replaces an existing
protocol handler.
### `protocol.uninterceptProtocol(scheme)`
* `scheme` String
Returns `Boolean` - Whether the protocol was successfully unintercepted
2016-10-13 06:30:57 +00:00
Remove the interceptor installed for `scheme` and restore its original handler.
### `protocol.isProtocolIntercepted(scheme)`
* `scheme` String
Returns `Boolean` - Whether `scheme` is already intercepted.
2016-08-24 16:03:44 +00:00
[file-system-api]: https://developer.mozilla.org/en-US/docs/Web/API/LocalFileSystem