* chore: initial prototype of net api from utility process * chore: update url loader to work on both browser and utility processes * chore: add net files to utility process bundle * chore: re-add app ready check but only on main process * chore: replace browser thread dcheck's with sequence checker * refactor: move url loader from browser to common * refactor: move net-client-request.ts from browser to common * docs: add utility process to net api docs * refactor: move net module app ready check to browser only * refactor: switch import from main to common after moving to common * test: add basic net module test for utility process * refactor: switch browser pid with utility pid * refactor: move electron_api_net from browser to common * chore: add fetch to utility net module * chore: add isOnline and online to utility net module * refactor: move net spec helpers into helper file * refactor: break apart net module tests Adds two additional net module test files: `api-net-session-spec.ts` for tests that depend on a session being available (aka depend on running on the main process) and `api-net-custom-protocols-spec.ts` for custom protocol tests. This enables running `api-net-spec.ts` in the utility process. * test: add utility process mocha runner to run net module tests * docs: add utility process to net module classes * refactor: update imports in lib/utility to use electron/utility * chore: check browser context before using in main process Since the browser context supplied to the SimpleURLLoaderWrapper can now be null for use in the UtilityProcess, adding a null check for the main process before use to get a more sensible error if something goes wrong. Co-authored-by: Cheng Zhao <github@zcbenz.com> * chore: remove test debugging * chore: remove unnecessary header include * docs: add utility process net module limitations * test: run net module tests in utility process individually * refactor: clean up prior utility process net tests * chore: add resolveHost to utility process net module * chore: replace resolve host dcheck with sequence checker * test: add net module tests for net.resolveHost * docs: remove utility process limitation for resolveHost --------- Co-authored-by: deepak1556 <hop2deep@gmail.com> Co-authored-by: Cheng Zhao <github@zcbenz.com>
7.3 KiB
net
Issue HTTP/HTTPS requests using Chromium's native networking library
The net
module is a client-side API for issuing HTTP(S) requests. It is
similar to the HTTP and
HTTPS modules of Node.js but uses
Chromium's native networking library instead of the Node.js implementation,
offering better support for web proxies. It also supports checking network status.
The following is a non-exhaustive list of why you may consider using the net
module instead of the native Node.js modules:
- Automatic management of system proxy configuration, support of the wpad protocol and proxy pac configuration files.
- Automatic tunneling of HTTPS requests.
- Support for authenticating proxies using basic, digest, NTLM, Kerberos or negotiate authentication schemes.
- Support for traffic monitoring proxies: Fiddler-like proxies used for access control and monitoring.
The API components (including classes, methods, properties and event names) are similar to those used in Node.js.
Example usage:
const { app } = require('electron')
app.whenReady().then(() => {
const { net } = require('electron')
const request = net.request('https://github.com')
request.on('response', (response) => {
console.log(`STATUS: ${response.statusCode}`)
console.log(`HEADERS: ${JSON.stringify(response.headers)}`)
response.on('data', (chunk) => {
console.log(`BODY: ${chunk}`)
})
response.on('end', () => {
console.log('No more data in response.')
})
})
request.end()
})
The net
API can be used only after the application emits the ready
event.
Trying to use the module before the ready
event will throw an error.
Methods
The net
module has the following methods:
net.request(options)
options
(ClientRequestConstructorOptions | string) - TheClientRequest
constructor options.
Returns ClientRequest
Creates a ClientRequest
instance using the provided
options
which are directly forwarded to the ClientRequest
constructor.
The net.request
method would be used to issue both secure and insecure HTTP
requests according to the specified protocol scheme in the options
object.
net.fetch(input[, init])
input
string | GlobalRequestinit
RequestInit & { bypassCustomProtocolHandlers?: boolean } (optional)
Returns Promise<GlobalResponse>
- see Response.
Sends a request, similarly to how fetch()
works in the renderer, using
Chrome's network stack. This differs from Node's fetch()
, which uses
Node.js's HTTP stack.
Example:
async function example () {
const response = await net.fetch('https://my.app')
if (response.ok) {
const body = await response.json()
// ... use the result.
}
}
This method will issue requests from the default
session. To send a fetch
request from
another session, use ses.fetch().
See the MDN documentation for
fetch()
for more
details.
Limitations:
net.fetch()
does not support thedata:
orblob:
schemes.- The value of the
integrity
option is ignored. - The
.type
and.url
values of the returnedResponse
object are incorrect.
By default, requests made with net.fetch
can be made to custom
protocols as well as file:
, and will trigger
webRequest handlers if present. When the non-standard
bypassCustomProtocolHandlers
option is set in RequestInit, custom protocol
handlers will not be called for this request. This allows forwarding an
intercepted request to the built-in handler. webRequest
handlers will still be triggered when bypassing custom protocols.
protocol.handle('https', (req) => {
if (req.url === 'https://my-app.com') {
return new Response('<body>my app</body>')
} else {
return net.fetch(req, { bypassCustomProtocolHandlers: true })
}
})
Note: in the utility process custom protocols are not supported.
net.isOnline()
Returns boolean
- Whether there is currently internet connection.
A return value of false
is a pretty strong indicator that the user
won't be able to connect to remote sites. However, a return value of
true
is inconclusive; even if some link is up, it is uncertain
whether a particular connection attempt to a particular remote site
will be successful.
net.resolveHost(host, [options])
host
string - Hostname to resolve.options
Object (optional)queryType
string (optional) - Requested DNS query type. If unspecified, resolver will pick A or AAAA (or both) based on IPv4/IPv6 settings:A
- Fetch only A recordsAAAA
- Fetch only AAAA records.
source
string (optional) - The source to use for resolved addresses. Default allows the resolver to pick an appropriate source. Only affects use of big external sources (e.g. calling the system for resolution or using DNS). Even if a source is specified, results can still come from cache, resolving "localhost" or IP literals, etc. One of the following values:any
(default) - Resolver will pick an appropriate source. Results could come from DNS, MulticastDNS, HOSTS file, etcsystem
- Results will only be retrieved from the system or OS, e.g. via thegetaddrinfo()
system calldns
- Results will only come from DNS queriesmdns
- Results will only come from Multicast DNS querieslocalOnly
- No external sources will be used. Results will only come from fast local sources that are available no matter the source setting, e.g. cache, hosts file, IP literal resolution, etc.
cacheUsage
string (optional) - Indicates what DNS cache entries, if any, can be used to provide a response. One of the following values:allowed
(default) - Results may come from the host cache if non-stalestaleAllowed
- Results may come from the host cache even if stale (by expiration or network changes)disallowed
- Results will not come from the host cache.
secureDnsPolicy
string (optional) - Controls the resolver's Secure DNS behavior for this request. One of the following values:allow
(default)disable
Returns Promise<ResolvedHost>
- Resolves with the resolved IP addresses for the host
.
This method will resolve hosts from the default session. To resolve a host from another session, use ses.resolveHost().
Properties
net.online
Readonly
A boolean
property. Whether there is currently internet connection.
A return value of false
is a pretty strong indicator that the user
won't be able to connect to remote sites. However, a return value of
true
is inconclusive; even if some link is up, it is uncertain
whether a particular connection attempt to a particular remote site
will be successful.