Permalink
Switch branches/tags
1-3-x 1-4-x 1-5-x 1-6-x 1-7-x 1-8-x 2-0-x 2-1-x 3-0-x-appcontainer-trials 3-0-x 3-1-x 4-0-x 69_enable_logging add-args-spec add-vsts-status-to-readme add-web-frame-add-origin-access-whitelist-entry appcontainer-trials appveyor-test-reporter appveyor_gpu_test asan-tests backport-release-notes_4-0-x better-spec-runner brenca/accessibility-tests brenca/cookie-store-backport-4-0-x brenca/fix-14908 brenca/fix-paste-and-match-style-3-0-x build-gn buildFromTemplate-fix chromium-upgrade/71 cleanup-build-dirs-vsts deprecate-webframe-api dialog-refactor-p1 disable-color-correct-rendering docs-index e2e enable-mixed-sandbox enable-power-monitor-tests expect-browser-window-spec expect-crash-reporter-spec export-patches fetch-electron fetch_job_uaf_patch fix-build-with-enable_run_as_node-disabled fix-drag-region-crash fix-last-crash-report fix-memory-tracing fix-mixed-sandbox-tests fix-power-observer-dbus_3-0-x fix-remote-debugging fix-vsts-mac-gn fix-window-close fix-windows-release-test fix-zoom-in-mac gn-add-nonproprietary-ffmpeg gn-babel gn-ci-builds gn-ci-sccache gn-circleci-mac gn-release-win gn-resource-conflict-omg-again-srsly gn-win-link ipc-filter jest-spike kthulu120/moveTopBackport lang lenient-locale-mkdirs make-cppcheck-happy master menu-accel migrate-setpath-logs miniak/chrome-extension miniak/desktop-capturer-filtering miniak/dock-api miniak/drop-mavericks miniak/fix-patch-description miniak/object-shorthand miniak/prefer-spread miniak/refactoring miniak/remote-promise-invoke miniak/remove-deprecated miniak/return-type-annotation miniak/screen-reader-detection miniak/tray-focus mkt/add-debugging-tools-to-windows-docs more-timeout multiple-globals no-chrome-common no-exit-event nornagon/gn-ci-builds ppontes/8100-backport-window.opener-null-fix-to-3-0-x ppontes/8100-use-proper-site-instance-candidate promise-changes promisify-affinity-tests promisify-cookies promisify-importcert promisify-tests publish-nightly-to-nightly reenable-nativeimage-specs release-1-7-x remove-blink_local_frame.patch rename-electron-build-configs resource-file-conflict-patch-explanation restore-clipboard-dcheck restore-url-dchecks restore-wtf-string-dcheck revert-10204-fix-window-opener revert-12293-revert-12193-master revert-15698-ppontes/8100-backport-window.opener-null-fix-to-4 rich-dialog roll-libcc route-permission-checks sandbox-ci-test single-core-fix-2-0-x single-core-fix-3-1-x system_netwok_context t-g test-build-appx test-change test-cr test-dirty-frame test-skips test-symbols-win unsafe-secure-origins url_fetcher_rewrite v2-sandbox wc-exec-js webui-resources webview-in-sandbox-renderer win-width-fix windows-powermonitor-shutdown-event wrap-docs-toc-in-element yolo-tests
Nothing to show
Find file Copy path
379 lines (298 sloc) 11.6 KB

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

Methods

The protocol module has the following methods:

protocol.registerStandardSchemes(schemes[, options])

  • schemes String[] - Custom schemes to be registered as standard schemes.
  • options Object (optional)
    • secure Boolean (optional) - true to register the scheme as secure. Default false.

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:

const { app, protocol } = require('electron')

protocol.registerStandardSchemes(['atom'])
app.on('ready', () => {
  protocol.registerHttpProtocol('atom', '...')
})

Note: This method can only be used before the ready event of the app module gets emitted.

protocol.registerServiceWorkerSchemes(schemes)

  • schemes String[] - Custom schemes to be registered to handle service workers.

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

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:, so you probably want to call protocol.registerStandardSchemes to have your scheme treated as a standard scheme.

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

  • scheme String
  • handler Function
    • request Object
      • url String
      • referrer String
      • method String
      • uploadData UploadData[]
    • callback Function
  • 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 (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 (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
  • 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 (optional)
    • error Error

Unregisters the custom protocol of 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.

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 (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 (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 (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
  • 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 (optional)
    • error Error

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