Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

Electron session module


May 25, 2021 Electron


Table of contents


session module can be used to create a Session object.

You can also use a session that already has a session property session of webContents webContents is BrowserWindow

const BrowserWindow = require('electron').BrowserWindow;

var win = new BrowserWindow({ width: 800, height: 600 });
win.loadURL("http://github.com");

var ses = win.webContents.session;

Method

session module has the following approach:

session.fromPartition(partition)

  • partition String

A new partition instance is returned from Session

If partition persist: then this page will use a persistent session, which will be available for all page applications. If there is no prefix, this page will use a historical session. If partition empty, the app's default session will be returned .

Property

session module has the following properties:

session.defaultSession

Returns the app's default session object.

Class: Session

You session create a Session object in Session module:

const session = require('electron').session;

var ses = session.fromPartition('persist:name');

The instance event

Instance Session the following events:

Event: 'will-download'

Triggered when Electron is about to download item from webContents item

Calling event.preventDefault() the download and this item is not available in the next item of the process.

session.defaultSession.on('will-download', function(event, item, webContents) {
  event.preventDefault();
  require('request')(item.getURL(), function(data) {
    require('fs').writeFileSync('/somewhere', data);
  });
});

The instance method

Instance Session the following methods:

ses.cookies

cookies give you every effort to query and modify cookies. For example:

// 查询所有 cookies.
session.defaultSession.cookies.get({}, function(error, cookies) {
  console.log(cookies);
});

// 查询与指定 url 相关的所有 cookies.
session.defaultSession.cookies.get({ url : "http://www.github.com" }, function(error, cookies) {
  console.log(cookies);
});

// 设置 cookie;
// may overwrite equivalent cookies if they exist.
var cookie = { url : "http://www.github.com", name : "dummy_name", value : "dummy" };
session.defaultSession.cookies.set(cookie, function(error) {
  if (error)
    console.error(error);
});

ses.cookies.get(filter, callback)

  • filter Object
    • url String (optional) - url associated with obtaining url .
    • name String (optional) - filter cookies through name.
    • domain String (optional) - Get cookies for the corresponding domain name or sub-domain name .
    • path String (optional) - Get cookies for the corresponding path .
    • secure Boolean (optional) - filter cookies through security.
    • session Boolean (optional) - filter out sessions or persistent cookies.
  • callback Function

Send a request in the hope of getting all the cookies that match details and callback(error, cookies) callback .

cookies are a cookie object.

  • cookie Object
    • name String - cookie name.
    • value String - cookie value.
    • domain String - cookie domain name.
    • hostOnly String - Whether a cookie is a host-only cookie.
    • path String - cookie path.
    • secure Boolean - is it a security cookie.
    • httpOnly Boolean - Whether it's just HTTP cookies.
    • session Boolean - Whether the cookie is a session cookie or a persistent cookie with a due date .
    • expirationDate Double (optional) - The due date of the cookie, the number of seconds since the UNIX era. Not available for session cookies.

ses.cookies.set(details, callback)

  • details Object
    • url String - url associated with obtaining url .
    • name String - cookie name. Ignore the default is empty.
    • value String - cookie value. Ignore the default is empty.
    • domain String - the domain name of the cookie. Ignoring the default is empty.
    • path String - the path of the cookie. Ignoring the default is empty.
    • secure Boolean - Whether a security identity has been made. The default is false.
    • session Boolean - whether it has been identified by HttpOnly. The default is false.
    • expirationDate Double - The due date of the cookie is the number of seconds since the UNIX era. If ignored, the cookie becomes a session cookie.
  • callback Function

Use details to set cookies, and when callback(error) to drop a callback .

ses.cookies.remove(url, name, callback)

  • url String - url associated with url .
  • name String - The name of the cookie that needs to be deleted.
  • callback Function

Remove the url that match name and name and callback when callback callback() .

ses.getCacheSize(callback)

  • callback Function
    • size Integer - cache size in units bytes.

Returns the current cache size of the session .

ses.clearCache(callback)

  • callback Function - Called when the operation is complete

Empty session's HTTP cache.

ses.clearStorageData([options, ]callback)

  • options Object (optional)
    • origin String - Should follow the format of window.location.origin scheme://host:port .
    • storages Array - Storages types that need to be cleaned up, which can appcache filesystem indexdb local storage shadercache websql serviceworkers cookies
    • quotas Array - Type metrics that need to be cleaned up, which can temporary persistent syncable .
  • callback Function - Called when the operation is complete.

Clear the data for web storages.

ses.flushStorageData()

Write DOMStorage that is not written to disk.

ses.setProxy(config, callback)

  • config Object
    • pacScript String - URL related to PAC file.
    • proxyRules String - Agent usage rules.
  • callback Function - Called when the operation is complete.

Set proxy settings.

When pacScript is proxyRules proxyRules and the pacScript .

proxyRules to follow the following rules:

proxyRules = schemeProxies[";"<schemeProxies>]
schemeProxies = [<urlScheme>"="]<proxyURIList>
urlScheme = "http" | "https" | "ftp" | "socks"
proxyURIList = <proxyURL>[","<proxyURIList>]
proxyURL = [<proxyScheme>"://"]<proxyHost>[":"<proxyPort>]

Example:

  • http=foopy:80;ftp=foopy2 - use the HTTP proxy foopy:80 for the http:// URL, and the http proxy foopy:80 for ftp:// URL http proxy foopy2:80 .
  • foopy:80 - Use the HTTP proxy foopy:80 .
  • foopy:80,bar,direct:// Use http proxy foopy:80 for all URLs, switch to bar if foopy:80 is not bar and then do not use proxy later.
  • socks4://foopy - Use SOCKS v4 proxy foopy:1080 .
  • http=foopy,socks5://bar.com - Uses http proxy foopy for all foopy and switches to SOCKS5 agent if foopy bar.com .
  • http=foopy,direct:// foopy
  • http=foopy;socks=foopy2 - use foopy agents for all http url and socks4://foopy2

ses.resolveProxy(url, callback)

  • url URL
  • callback Function

Resolve the proxy information for the url Callback is called callback(proxy) callback .

ses.setDownloadPath(path)

  • path String - Download address

Set the download save address, the default save address is the Downloads directory of their respective app apps.

ses.enableNetworkEmulation(options)

  • options Object
    • offline Boolean - Whether to simulate a network failure.
    • latency Double - RTT per millisecond
    • downloadThroughput Double - Download rate per Bps.
    • uploadThroughput Double - upload rate per Bps.

Simulate the network with session configured session.

// 模拟 GPRS 连接,使用的 50kbps 流量,500 毫秒的 rtt.
window.webContents.session.enableNetworkEmulation({
    latency: 500,
    downloadThroughput: 6400,
    uploadThroughput: 6400
});

// 模拟网络故障.
window.webContents.session.enableNetworkEmulation({offline: true});

ses.disableNetworkEmulation()

Stop all active analog networks that already use session Reset to the original network type.

ses.setCertificateVerifyProc(proc)

  • proc Function

Set up a certificate validation process for session when requesting certificate validation for a server, use proc(hostname, certificate, callback) to call proc callback(true) to receive the callback(false) to deny the authentication certificate.

Called setCertificateVerifyProc(null) will be reverted to the default certificate verification process.

myWindow.webContents.session.setCertificateVerifyProc(function(hostname, cert, callback) {
  if (hostname == 'github.com')
    callback(true);
  else
    callback(false);
});

ses.setPermissionRequestHandler(handler)

  • handler Function
    • webContents Object - WebContents request permission.
    • permission String - Enumerations 'media', 'geolocation', 'notifications', 'midiSysex', 'pointerLock', 'fullscreen'.
    • callback Function - Allow or prohibit licensing.

Set the session for the corresponding session license request. Call callback(true) to receive licenses, callback(false) licenses.

session.fromPartition(partition).setPermissionRequestHandler(function(webContents, permission, callback) {
  if (webContents.getURL() === host) {
    if (permission == "notifications") {
      callback(false); // denied.
      return;
    }
  }

  callback(true);
});

ses.clearHostResolverCache([callback])

  • callback Function (optional) - Operation end call.

Clear the host resolution cache.

ses.webRequest

At different stages of its lifecycle, webRequest API settings allow you to intercept and modify requested content.

Each API receives an optional filter filter listener which are called listener when the API event listener(details) and listener details object used to describe the request. Using listener for null desegress the event.

filter is an object with urls which is an array of url patterns that filter out requests that do not match the specified url pattern. If filter is filter all requests will match successfully.

The listener events has a callback event that will be called with a response object when the listener response its work.

// 将所有请求的代理都修改为下列 url.
var filter = {
  urls: ["https://*.github.com/*", "*://electron.github.io"]
};

session.defaultSession.webRequest.onBeforeSendHeaders(filter, function(details, callback) {
  details.requestHeaders['User-Agent'] = "MyAgent";
  callback({cancel: false, requestHeaders: details.requestHeaders});
});

ses.webRequest.onBeforeRequest([filter, ]listener)

  • filter Object
  • listener Function

When a request is about to begin, call the listener(details, callback) listener .

  • details Object
    • id Integer
    • url String
    • method String
    • resourceType String
    • timestamp Double
    • uploadData Array (optional)
  • callback Function

uploadData is a data array object:

  • data Object
    • bytes Buffer - What is being sent.
    • file String - Upload file path.

callback must use a response object to call:

  • response Object
    • cancel Boolean (optional)
    • redirectURL String (optional) - The original request is blocked from being sent or completed instead of redirecting.

ses.webRequest.onBeforeSendHeaders([filter, ]listener)

  • filter Object
  • listener Function

Once the request message header is available, call listener(details, callback) before sending the HTTP request. This may initiate a listener connection on the server, but it occurs before any http data is sent.

  • details Object
    • id Integer
    • url String
    • method String
    • resourceType String
    • timestamp Double
    • requestHeaders Object
  • callback Function

You must use a response object to callback :

  • response Object
    • cancel Boolean (optional)
    • requestHeaders Object (optional) - If provided, these headers will be used to create requests.

ses.webRequest.onSendHeaders([filter, ]listener)

  • filter Object
  • listener Function

When a request is being sent to the listener(details) is used to call listener before onBeforeSendHeaders part of the response is available while de-listening.

  • details Object
    • id Integer
    • url String
    • method String
    • resourceType String
    • timestamp Double
    • requestHeaders Object

ses.webRequest.onHeadersReceived([filter,] listener)

  • filter Object
  • listener Function

When the HTTP request message header has arrived, call the listener(details, callback) listener .

  • details Object
    • id String
    • url String
    • method String
    • resourceType String
    • timestamp Double
    • statusLine String
    • statusCode Integer
    • responseHeaders Object
  • callback Function

You must use a response object to callback :

  • response Object
    • cancel Boolean
    • responseHeaders Object (optional) - If provided, the server will assume that these heads are used to respond.

ses.webRequest.onResponseStarted([filter, ]listener)

  • filter Object
  • listener Function

When the first byte of the response body arrives, call listener using listener(details) For http requests, this means that the status line and response header are available.

  • details Object
    • id Integer
    • url String
    • method String
    • resourceType String
    • timestamp Double
    • responseHeaders Object
    • fromCache Boolean - Identify whether the response came from disk cache.
    • statusCode Integer
    • statusLine String

ses.webRequest.onBeforeRedirect([filter, ]listener)

  • filter Object
  • listener Function

When the server's redirection initialization is about to listener(details) listener .

  • details Object
    • id String
    • url String
    • method String
    • resourceType String
    • timestamp Double
    • redirectURL String
    • statusCode Integer
    • ip String (optional) - The requested real server ip address
    • fromCache Boolean
    • responseHeaders Object

ses.webRequest.onCompleted([filter, ]listener)

  • filter Object
  • listener Function

When the request is complete, call the listener(details) listener .

  • details Object
    • id Integer
    • url String
    • method String
    • resourceType String
    • timestamp Double
    • responseHeaders Object
    • fromCache Boolean
    • statusCode Integer
    • statusLine String

ses.webRequest.onErrorOccurred([filter, ]listener)

  • filter Object
  • listener Function

When an error occurs, listener(details) listener .

  • details Object
    • id Integer
    • url String
    • method String
    • resourceType String
    • timestamp Double
    • fromCache Boolean
    • error String - Misscriptive.