Session

The session module can be used to create or access the browser session present inside each renderer process or the rendered page. The events and methods provided by the session object are very useful: proxy the requests, intercepting the content download and emulating the network usage, and so on. Let's look into the details of the session API.

Session API is a getter property available under web content API. This means that you can access the session of the current page using session property of web content API. We will discuss web content API later in this book. Here is the basic example of getting the current session of a web page inside Electron shell:

const { session, app, BrowserWindow } = require('electron');

let appShell;
const appUrl = `file://${__dirname}/index.html`;

function createElectronShell() {
appShell = new BrowserWindow({ width: 800, height: 600 });
appShell.loadURL(appUrl);
// Get default session object
const ses = appShell.webContents.session;
console.log(ses.getUserAgent());
}
app.on('ready', createElectronShell);

Here, we got a session object already defined with the current window object. To instantiate or create a new session object from scratch, the session.fromPartition method can be used. You can use the following code to instantiate the session:

const { session } = require('electron');
const _session = session.fromPartition('persist:name');

// Get the user agent from the session object
console.log(_session.getUserAgent());

This code will return a session object from the partition if it exists, else it will create a new session object from scratch and return it to the _session variable. Here, partition means from where it should get the session object reference. You need to take care of the following points when working with partitions:

  • If the value of the partition starts with partition, the page will use a persistent session available to all pages in the app with the same partition. For example,  session.fromPartition('persist:name') will check all the pages inside the app for the session with a 'persist' value equal to its name.
  • If there is no persist: prefix, the page will use an in-memory session. If the partition is empty, then default session of the app will be returned.

To create a session with options, you have to ensure that the session with the partition has never been used before. There is no way to change the options of an existing session object.

The session can accept an optional second argument, which can be used to enable or disable cache. However, to use this optional argument, you need to ensure that the session with the same persist name has never been used before. Once you initialize a session with options, you cannot change it.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.191.176.194