new·The score now tells you which way it movedA brain's exam only ever grows: its own material writes questions, and so does every question a real caller asked and did not get answered. The score is a percentage over that growing set, so a brain that learned more could post a smaller number — and this week three did. One of them answered two MORE questions than the week before and showed eighteen points less. Printed as a single percentage, that reads as decline to a reader and as punishment to anyone who contributes material.all news →
mozg.beta
Sign in

Electron · API · all subjects

app/network

62 notes in this subject, read out of this brain and free to use. This is page 1 of 2.

app.userAgentFallback property

A string property which is the user agent string Electron will use as a global fallback. This is the user agent that will be used when no user agent is set at the webContents or session level. It is useful for ensuring that your entire app has the same user agent. Set to a custom value as early as possible in your app's initialization to ensure that your overridden value is used.

app.resolveProxy(url) method

The app.resolveProxy(url) method accepts a URL parameter and returns Promise<string> that resolves with the proxy information for that URL. This is the proxy that will be used when attempting to make requests using Net in the utility process.

app.setProxy(config) method

The app.setProxy(config) method accepts a ProxyConfig object and returns Promise<void> that resolves when the proxy setting process is complete. Sets proxy settings for network requests made without an associated Session. Currently affects requests made with Net in the utility process and internal requests made by the runtime such as geolocation queries. This method can only be called after the app is ready.

ClientRequest class overview

ClientRequest is a class for making HTTP/HTTPS requests in Electron. It is available in the Main and Utility processes. It is not exported from the 'electron' module but returned as a value from other Electron API methods. ClientRequest implements the Writable Stream interface and is an EventEmitter.

ClientRequest constructor options

ClientRequest constructor accepts options (Object | string). If string, it is interpreted as the request URL. If object, the following properties are supported: method (string, optional): HTTP request method. Defaults to GET. url (string, optional): Request URL in absolute form with protocol scheme (http or https). headers (Record<string, string | string[]>, optional): Headers to send with request. session (Session, optional): Session instance associated with the request. partition (string, optional): Partition name associated with the request. Defaults to empty string. Session option supersedes partition. bypassCustomProtocolHandlers (boolean, optional): If true, custom protocol handlers registered for the request's URL scheme are not called. webRequest handlers still trigger. Defaults to false. credentials (string, optional): Can be 'include', 'omit', or 'same-origin'. Whether to send credentials. 'include' uses session credentials, 'omit' prevents credentials and 'login' event, 'same-origin' requires origin to be specified. Defaults to sending authentication data but not cookies unless useSessionCookies is set. useSessionCookies (boolean, optional): Whether to send cookies from session with request. No effect if credentials is specified. Defaults to false. protocol (string, optional): Can be 'http:' or 'https:'. Defaults to 'http:'. host (string, optional): Server host as 'hostname:port'. hostname (string, optional): Server host name. port (Integer, optional): Server listening port number. path (string, optional): Path part of request URL. redirect (string, optional): Can be 'follow', 'error', or 'manual'. Redirect mode. 'error' aborts redirection, 'manual' cancels unless request.followRedirect() is called during redirect event. Defaults to 'follow'. origin (string, optional): Origin URL of the request. referrerPolicy (string, optional): Can be empty string, 'no-referrer', 'no-referrer-when-downgrade', 'origin', 'origin-when-cross-origin', 'unsafe-url', 'same-origin', 'strict-origin', or 'strict-origin-when-cross-origin'. Defaults to 'strict-origin-when-cross-origin'. cache (string, optional): Can be 'default', 'no-store', 'reload', 'no-cache', 'force-cache', or 'only-if-cached'. priority (string, optional): Can be 'throttled', 'idle', 'lowest', 'low', 'medium', or 'highest'. Defaults to 'idle'. priorityIncremental (boolean, optional): Incremental loading flag as part of HTTP extensible priorities (RFC 9218). Defaults to true.

ClientRequest 'response' event

The 'response' event is emitted when the HTTP response message is received. It returns an IncomingMessage object representing the HTTP response.

ClientRequest 'login' event

The 'login' event is emitted when an authenticating proxy asks for user credentials. Returns authInfo object with properties: isProxy (boolean), scheme (string), host (string), port (Integer), realm (string); and a callback function. The callback function must be called with username (string, optional) and password (string, optional) to provide credentials. Calling callback with no arguments cancels the request and reports authentication error on response object.

ClientRequest 'error' event

The 'error' event is emitted when the net module fails to issue a network request. Returns an error object providing information about the failure. Typically when error event is emitted, a close event will subsequently follow and no response object will be provided.

ClientRequest 'close' event

The 'close' event is emitted as the last event in the HTTP request-response transaction. It indicates that no more events will be emitted on either the request or response objects.

ClientRequest 'redirect' event

The 'redirect' event is emitted when the server returns a redirect response (e.g. 301 Moved Permanently). Returns statusCode (Integer), method (string), redirectUrl (string), and responseHeaders (Record<string, string[]>). Calling request.followRedirect() continues with redirection. If this event is handled, request.followRedirect() must be called synchronously, otherwise the request will be cancelled.

ClientRequest chunkedEncoding property

request.chunkedEncoding is a boolean property specifying whether the request will use HTTP chunked transfer encoding or not. Defaults to false. The property is readable and writable, but can only be set before the first write operation as HTTP headers are not yet on the wire. Trying to set it after first write throws an error. Chunked encoding is strongly recommended for large request bodies as data is streamed in small chunks instead of being internally buffered.

ClientRequest setHeader method

request.setHeader(name, value) adds an extra HTTP header. Parameters: name (string) - header name, value (string) - header value. The header name is issued as-is without lowercasing. Can only be called before first write; calling after first write throws error. If passed value is not string, its toString() method is called. Certain headers are restricted: Content-Length, Host, Trailer, Te, Upgrade, Cookie2, Keep-Alive, Transfer-Encoding. Setting Connection header to 'upgrade' is also disallowed.

ClientRequest getHeader method

request.getHeader(name) returns the value of a previously set extra header. Parameters: name (string) - extra header name to retrieve. Returns string value of the header.

ClientRequest removeHeader method

request.removeHeader(name) removes a previously set extra header. Parameters: name (string) - extra header name to remove. Can only be called before first write; calling after first write throws error.

ClientRequest write method

request.write(chunk[, encoding][, callback]) adds a chunk of data to the request body. Parameters: chunk (string | Buffer) - chunk of request body data; encoding (string, optional) - used to convert string chunks to Buffer, defaults to 'utf-8'; callback (Function, optional) - called after write operation ends. The callback is called asynchronously in the next tick after chunk content is delivered to Chromium networking layer, but it is not guaranteed that chunk content is flushed on the wire before callback is called. First write operation may cause request headers to be issued on wire. After first write, adding or removing custom headers is not allowed.

ClientRequest end method

request.end([chunk][, encoding][, callback]) sends the last chunk of request data and returns this. Parameters: chunk (string | Buffer, optional), encoding (string, optional), callback (Function, optional). Subsequent write or end operations are not allowed. The finish event is emitted just after the end operation.

ClientRequest abort method

request.abort() cancels an ongoing HTTP transaction. If the request has already emitted the close event, abort has no effect. Otherwise, an ongoing request will emit abort and close events. If there is an ongoing response object, it will emit the aborted event.

ClientRequest followRedirect method

request.followRedirect() continues any pending redirection. Can only be called during a 'redirect' event.

ClientRequest getUploadProgress method

request.getUploadProgress() returns an Object with the following properties: active (boolean) - whether request is currently active; if false, no other properties are set. started (boolean) - whether upload has started; if false, both current and total are 0. current (Integer) - number of bytes uploaded so far. total (Integer) - number of bytes that will be uploaded this request. This method is useful with POST requests to get progress of file upload or other data transfer.

ClientRequest example with protocol, hostname, port, and path

const request = net.request({ method: 'GET', protocol: 'https:', hostname: 'github.com', port: 443, path: '/' })

ClientRequest 'login' event example

request.on('login', (authInfo, callback) => { callback('username', 'password') })

ClientRequest 'finish' event

The 'finish' event is emitted just after the last chunk of the request's data has been written into the request object.

ClientRequest 'abort' event

The 'abort' event is emitted when the request is aborted. The abort event will not be fired if the request is already closed.

--proxy-bypass-list switch

The --proxy-bypass-list=hosts switch instructs Electron to bypass the proxy server for a given semi-colon-separated list of hosts. This flag only has an effect if used with --proxy-server. Example: app.commandLine.appendSwitch('proxy-bypass-list', '<local>;*.google.com;*foo.com;1.2.3.4:5678') will use the proxy server for all hosts except local addresses (localhost, 127.0.0.1 etc.), google.com subdomains, hosts containing foo.com suffix, and 1.2.3.4:5678.

--proxy-pac-url switch

The --proxy-pac-url=url switch uses the PAC script at the specified URL.

--proxy-server switch

The --proxy-server=address:port switch uses a specified proxy server, which overrides the system setting. This switch only affects requests with HTTP protocol, including HTTPS and WebSocket requests. Not all proxy servers support HTTPS and WebSocket requests. The proxy URL does not support username and password authentication per Chromium issue 615947.

ProtocolResponseUploadData object structure

The ProtocolResponseUploadData object has two properties: contentType (string, required) for the MIME type of the content, and data (string or Buffer, required) for the content to be sent.

ProxyConfig proxyRules examples

Examples of proxyRules: (1) http=foopy:80;ftp=foopy2 - use HTTP proxy foopy:80 for http:// URLs and HTTP proxy foopy2:80 for ftp:// URLs; (2) foopy:80 - use HTTP proxy foopy:80 for all URLs; (3) foopy:80,bar,direct:// - use HTTP proxy foopy:80 for all URLs, failing over to bar if foopy:80 is unavailable, then use no proxy; (4) socks4://foopy - use SOCKS v4 proxy foopy:1080 for all URLs; (5) http=foopy,socks5://bar.com - use HTTP proxy foopy for http URLs, fail over to SOCKS5 proxy bar.com if foopy is unavailable; (6) http=foopy,direct:// - use HTTP proxy foopy for http URLs, use no proxy if foopy is unavailable; (7) http=foopy;socks=foopy2 - use HTTP proxy foopy for http URLs, use socks4://foopy2 for all other URLs.

ProxyConfig mode values and defaults

The ProxyConfig mode property is optional and accepts the following values: direct, auto_detect, pac_script, fixed_servers, or system. The default mode is pac_script if pacScript option is specified, otherwise defaults to fixed_servers. In direct mode all connections are created directly without any proxy. In auto_detect mode the proxy configuration is determined by a PAC script downloaded at http://wpad/wpad.dat. In pac_script mode the proxy configuration is determined by a PAC script retrieved from the URL specified in pacScript. In fixed_servers mode the proxy configuration is specified in proxyRules. In system mode the proxy configuration is taken from the operating system, which differs from setting no proxy configuration—Electron falls back to system settings only if no command-line options influence the proxy configuration.

ProxyConfig properties

ProxyConfig object has the following properties: mode (string, optional) - the proxy mode; pacScript (string, optional) - the URL associated with the PAC file; proxyRules (string, optional) - rules indicating which proxies to use; proxyBypassRules (string, optional) - rules indicating which URLs should bypass the proxy settings.

ProxyConfig pacScript and proxyRules precedence

When mode is unspecified and both pacScript and proxyRules are provided together, the proxyRules option is ignored and pacScript configuration is applied.

ProxyConfig proxyRules format specification

The proxyRules property follows this format specification: proxyRules = schemeProxies[";">schemeProxies], schemeProxies = [<urlScheme>"="]<proxyURIList>, urlScheme = "http" | "https" | "ftp" | "socks", proxyURIList = <proxyURL>[","<proxyURIList>], proxyURL = [<proxyScheme>"://"]<proxyHost>[":"<proxyPort>].

ProxyConfig proxyBypassRules format and patterns

The proxyBypassRules property is a comma-separated list of rules that match URLs to bypass proxy settings. Pattern types: (1) [ URL_SCHEME "://" ] HOSTNAME_PATTERN [ ":" <port> ] - matches all hostnames matching the pattern, examples: "foobar.com", "*foobar.com", "*.foobar.com", "*foobar.com:99", "https://x.*.y.com:99"; (2) "." HOSTNAME_SUFFIX_PATTERN [ ":" PORT ] - matches a particular domain suffix, examples: ".google.com", ".com", "http://.google.com"; (3) [ SCHEME "://" ] IP_LITERAL [ ":" PORT ] - matches URLs which are IP address literals, examples: "127.0.1", "[0:0::1]", "[::1]", "http://[::1]:99"; (4) IP_LITERAL "/" PREFIX_LENGTH_IN_BITS - matches any URL to an IP literal in the given range using CIDR notation, examples: "192.168.1.1/16", "fefe:13::abc/33"; (5) <local> - matches local addresses, the meaning is whether the host matches one of "127.0.0.1", "::1", "localhost".

WebRequestFilter object structure

The WebRequestFilter object contains the following properties: urls (required, string array), excludeUrls (optional, string array), and types (optional, string array). The urls property is an array of URL patterns that must match for requests to be included. URL patterns follow Mozilla's Add-ons WebExtensions Match pattern format, and the special pattern <all_urls> can be used to match all URLs. The excludeUrls property is an optional array of URL patterns used to exclude requests that match those patterns. The types property is an optional array of request types that will be used to filter requests; when not specified, all types are matched.

WebRequestFilter types property values

The types property of WebRequestFilter can contain the following values: mainFrame, subFrame, stylesheet, script, image, font, object, xhr, ping, cspReport, media, or webSocket.

WebSocketOptions protocols parameter

The protocols parameter is optional and accepts either a single string or an array of strings representing requested WebSocket subprotocols.

WebSocketOptions headers parameter

The headers parameter is optional and accepts a Record<string, string> containing extra HTTP headers to send with the WebSocket opening handshake.

WebSocketOptions origin parameter

The origin parameter is optional and specifies the value of the Origin header to send with the opening handshake. It defaults to the http(s) equivalent of the WebSocket URL's origin. For example, connecting to wss://api.example.com sends Origin: https://api.example.com by default, which treats the connection as same-origin by the server and by SameSite cookie rules.

WebSocketOptions useSessionCookies parameter

The useSessionCookies parameter is optional and is a boolean that controls whether to send cookies from the session with the opening handshake and store cookies received in the handshake response. It defaults to false.

WebSocketOptions session parameter

The session parameter is optional and accepts a Session object that the WebSocket connection is associated with.

WebSocketOptions partition parameter

The partition parameter is optional and accepts a string specifying the name of the partition the WebSocket connection is associated with. It defaults to the empty string, which corresponds to the default session. If the session parameter is provided, partition is ignored.

WebRequest class overview

WebRequest is a main-process class used to intercept and modify the contents of a request at various stages of its lifetime. It is not exported from the 'electron' module but is accessed as a return value via the webRequest property of a Session. Only the last attached listener will be used; passing null as listener will unsubscribe from the event.

WebRequest filter and listener parameters

WebRequest methods accept an optional filter parameter and a required listener parameter. The filter object has a urls property which is an Array of URL patterns used to filter requests. If filter is omitted, all requests will be matched. The listener is called with listener(details) when the event occurs, and for certain events the listener receives a callback parameter that should be called with a response object.

onErrorOccurred method

webRequest.onErrorOccurred([filter, ]listener) is called when an error occurs. Parameters: filter (WebRequestFilter, optional), listener (Function | null). The listener receives details object with properties: id (Integer), url (string), method (string), webContentsId (Integer, optional), webContents (WebContents, optional), frame (WebFrameMain | null, optional, may be null if accessed after frame navigation or destruction), resourceType (string: mainFrame, subFrame, stylesheet, script, image, font, object, xhr, ping, cspReport, media, webSocket or other), referrer (string), timestamp (Double), fromCache (boolean), error (string, the error description).

onSendHeaders method

webRequest.onSendHeaders([filter, ]listener) is called just before a request is going to be sent to the server. Modifications of previous onBeforeSendHeaders response are visible by the time this listener is fired. Parameters: filter (WebRequestFilter, optional), listener (Function | null). The listener receives details object with properties: id (Integer), url (string), method (string), webContentsId (Integer, optional), webContents (WebContents, optional), frame (WebFrameMain | null, optional, may be null if accessed after frame navigation or destruction), resourceType (string: mainFrame, subFrame, stylesheet, script, image, font, object, xhr, ping, cspReport, media, webSocket or other), referrer (string), timestamp (Double), requestHeaders (Record<string, string>).

onHeadersReceived method

webRequest.onHeadersReceived([filter, ]listener) is called when HTTP response headers of a request have been received. Parameters: filter (WebRequestFilter, optional), listener (Function | null). The listener receives details object with properties: id (Integer), url (string), method (string), webContentsId (Integer, optional), webContents (WebContents, optional), frame (WebFrameMain | null, optional, may be null if accessed after frame navigation or destruction), resourceType (string: mainFrame, subFrame, stylesheet, script, image, font, object, xhr, ping, cspReport, media, webSocket or other), referrer (string), timestamp (Double), statusLine (string), statusCode (Integer), responseHeaders (Record<string, string[]>, optional). The listener also receives a callback function that must be called with headersReceivedResponse object containing: cancel (boolean, optional), responseHeaders (Record<string, string | string[]>, optional, when provided server is assumed to have responded with these headers), statusLine (string, optional, should be provided when overriding responseHeaders to change header status otherwise original response header's status will be used).

onResponseStarted method

webRequest.onResponseStarted([filter, ]listener) is called when first byte of the response body is received. For HTTP requests this means the status line and response headers are available. Parameters: filter (WebRequestFilter, optional), listener (Function | null). The listener receives details object with properties: id (Integer), url (string), method (string), webContentsId (Integer, optional), webContents (WebContents, optional), frame (WebFrameMain | null, optional, may be null if accessed after frame navigation or destruction), resourceType (string: mainFrame, subFrame, stylesheet, script, image, font, object, xhr, ping, cspReport, media, webSocket or other), referrer (string), timestamp (Double), responseHeaders (Record<string, string[]>, optional), fromCache (boolean, indicates whether response was fetched from disk cache), statusCode (Integer), statusLine (string).

onBeforeRedirect method

webRequest.onBeforeRedirect([filter, ]listener) is called when a server initiated redirect is about to occur. Parameters: filter (WebRequestFilter, optional), listener (Function | null). The listener receives details object with properties: id (Integer), url (string), method (string), webContentsId (Integer, optional), webContents (WebContents, optional), frame (WebFrameMain | null, optional, may be null if accessed after frame navigation or destruction), resourceType (string: mainFrame, subFrame, stylesheet, script, image, font, object, xhr, ping, cspReport, media, webSocket or other), referrer (string), timestamp (Double), redirectURL (string), statusCode (Integer), statusLine (string), ip (string, optional, server IP address that the request was actually sent to), fromCache (boolean), responseHeaders (Record<string, string[]>, optional).

onCompleted method

webRequest.onCompleted([filter, ]listener) is called when a request is completed. Parameters: filter (WebRequestFilter, optional), listener (Function | null). The listener receives details object with properties: id (Integer), url (string), method (string), webContentsId (Integer, optional), webContents (WebContents, optional), frame (WebFrameMain | null, optional, may be null if accessed after frame navigation or destruction), resourceType (string: mainFrame, subFrame, stylesheet, script, image, font, object, xhr, ping, cspReport, media, webSocket or other), referrer (string), timestamp (Double), responseHeaders (Record<string, string[]>, optional), fromCache (boolean), statusCode (Integer), statusLine (string), error (string).

WebRequest URL pattern examples

Valid URL patterns for WebRequest filter include: '<all_urls>', 'http://foo:1234/', 'http://foo.com/', 'http://foo:1234/bar', '*://*/*', '*://example.com/*', '*://example.com/foo/*', 'http://*.foo:1234/', 'file://foo:1234/bar', 'http://foo:*/', '*://www.foo.com/'.

WebRequest User-Agent header modification example

Example code to modify the user agent for all requests to specific URLs: const { session } = require('electron') const filter = { urls: ['https://*.github.com/*', '*://electron.github.io/*'] } session.defaultSession.webRequest.onBeforeSendHeaders(filter, (details, callback) => { details.requestHeaders['User-Agent'] = 'MyAgent' callback({ requestHeaders: details.requestHeaders }) })

WebSocket class in net module

The net.WebSocket class extends EventTarget and provides a drop-in replacement for the WHATWG WebSocket interface. It routes connections through Chromium's network stack rather than Node.js and is only available in the main process. It can only be used after the application emits the ready event.

WebSocket features and capabilities

net.WebSocket uses the system or session proxy configuration (PAC, WPAD), validates TLS certificates against the platform trust store and the session's certificate verification policy, honors session-level configuration (custom CA, host resolution rules, etc.), and sends the session's cookies when useSessionCookies is enabled.

net.WebSocket constructor

The constructor is called as new net.WebSocket(url[, protocols]). The url parameter (required, string) must have a scheme of ws: or wss: (http: and https: are accepted and rewritten to their WebSocket equivalents). The protocols parameter (optional, string | string[] | WebSocketOptions) can be one or more WebSocket subprotocols, or an Electron-specific options object. Passing an options object is an Electron extension; the two-argument form is fully compatible with the WHATWG constructor.

WebSocket static properties for readyState constants

WebSocket provides four readonly static properties: CONNECTING equals 0 (readyState value while opening handshake is in progress), OPEN equals 1 (readyState value once connection is established), CLOSING equals 2 (readyState value while closing handshake is in progress), and CLOSED equals 3 (readyState value once connection is closed).

WebSocket instance properties

ws.url (readonly, string): the resolved URL of the connection. ws.readyState (readonly, integer): current state of the connection (0-3). ws.bufferedAmount (readonly, integer): number of bytes of application data queued via send() but not yet handed to the network. ws.protocol (readonly, string): subprotocol selected by the server, empty string until connection is open or if server did not select one. ws.extensions (readonly, string): extensions negotiated by the server, e.g. 'permessage-deflate'.

WebSocket binaryType property

ws.binaryType is a string property controlling how incoming binary messages are exposed on the message event. Can be 'nodebuffer', 'arraybuffer', or 'blob'. The default is 'nodebuffer'. 'nodebuffer' is an Electron extension that delivers binary messages as Buffer objects, which is generally the most convenient representation in the main process. Set binaryType to 'arraybuffer' or 'blob' for behavior identical to the renderer WebSocket.

WebSocket event handler properties

ws.onopen, ws.onmessage, ws.onerror, and ws.onclose are each a Function | null event handler property, equivalent to calling addEventListener() with the corresponding event name ('open', 'message', 'error', 'close').

WebSocket send method

The send method takes a data parameter (string | ArrayBufferLike | ArrayBufferView | Blob). Strings are sent as text frames; everything else is sent as a binary frame. The method enqueues data to be transmitted to the server. Throws an InvalidStateError DOMException if readyState is CONNECTING.

WebSocket close method

The close method optionally takes a code parameter (integer) which must be 1000 or in the range 3000–4999, and a reason parameter (string, optional) which is a human-readable close reason that must encode to no more than 123 bytes of UTF-8. Calling close() while still CONNECTING aborts the handshake.

Give your agent this brain