Contents

Session

Manage cookies, caches, browsing data, and the user agent.

The session object represents the browsing session shared by every browser in the application. Cookies, caches, local storage, and the other browsing data live in the session, so all web content loaded in your application’s windows shares them.

import { session } from '@mobrowser/api';

Browsing data location 

The session stores browsing data in the directory returned by the storagePath property:

console.log(`Browsing data lives in ${session.storagePath}`)

The directory is created when the application first starts. Treat it as a location to inspect or back up. Its contents aren’t part of the public API.

A persistent session keeps cookies, caches, and local storage across restarts. A non-persistent session keeps them in memory and discards them when the application quits. To find out which one your application uses, call isPersistent():

if (!session.isPersistent()) {
  console.log('Browsing data will be discarded on quit')
}

Cookies 

The session.cookies object gives you access to the cookie store of the session.

Getting cookies 

To get cookies, call get(). Called without a filter, it returns every cookie in the store:

const cookies = await session.cookies.get()

To get the cookies that a request to a specific URL would send, pass the URL. The scheme, host, and path of the URL are taken into account, so a secure cookie isn’t returned for an http:// URL, and a cookie scoped to /admin isn’t returned for /:

const cookies = await session.cookies.get({ url: 'https://example.com' })

You can also filter cookies by name, domain, path, secure, httpOnly, and session. A domain filter returns cookies stored at or below the domain, so { domain: 'example.com' } also returns cookies stored for www.example.com, but not for notexample.com:

const sessionCookies = await session.cookies.get({
  domain: 'example.com',
  session: true
})

To store a cookie, call set() with the URL the cookie is stored against:

await session.cookies.set({
  url: 'https://example.com',
  name: 'theme',
  value: 'dark',
  expirationDate: Date.now() / 1000 + 60 * 60 * 24 * 365
})

The domain and path of the cookie default to the host and path of the URL. Pass a domain with a leading dot to make the cookie apply to subdomains as well. Leave out expirationDate to store a session cookie, which is discarded when the application quits.

The promise is rejected when the cookie store refuses the cookie, for example a sameSite: 'noRestriction' cookie that isn’t secure.

To remove a cookie, pass the URL it applies to and its name:

await session.cookies.remove('https://example.com', 'token')

Removing a cookie that is not in the store succeeds and does nothing.

To get notified when a cookie is added, updated, or removed, subscribe to the changed event:

import { session, CookieChange } from '@mobrowser/api';

session.cookies.on('changed', (change: CookieChange) => {
  const { cookie, cause, removed } = change
  console.log(`${cookie.name} ${removed ? 'removed' : 'set'}: ${cause}`)
})

The cause property tells why the cookie changed. For example, 'explicit' means that the cookie was set or removed directly, and 'expired' means that it was removed because it expired.

Writing cookies to disk 

The cookie store writes persistent cookies to disk on its own schedule. When you need to be certain that they’ve been written, for example before the application quits through an unusual path, call flushStore():

await session.cookies.flushStore()

Clearing browsing data 

To remove browsing data, call clearData(). Called without options, it removes every kind of browsing data for every site:

await session.clearData()

Use the options to narrow what is removed:

  • dataTypes — the kinds of data to remove: 'cache', 'cookies', 'storage' (local storage, IndexedDB, service workers, and other storage a page writes itself), and 'downloads' (the record of completed downloads; the downloaded files stay on disk).
  • origins — the sites to remove the data of.
  • excludeOrigins — the sites to keep the data of. It can’t be combined with origins.
  • since — the time in seconds since the UNIX epoch. Only data recorded at or after this time is removed.

For example, the following code signs the user out of a site, and then removes everything recorded during the last hour:

// Sign the user out of one site.
await session.clearData({
  dataTypes: ['cookies', 'storage'],
  origins: ['https://example.com']
})

// Clear everything from the last hour.
await session.clearData({ since: Date.now() / 1000 - 3600 })

Note: Browsing data is scoped to a site rather than to a single origin, so origins and excludeOrigins apply to the whole registrable domain. An entry of https://mail.example.com removes the data of example.com and every host under it. A URL with an IP address or a host without a registrable domain, such as http://localhost:3000, applies to that host only.

An empty list is not the same as leaving an option out: session.clearData({ dataTypes: [] }) removes nothing.

Clearing caches 

The session provides separate methods to clear specific caches:

MethodDescription
getCacheSize()Returns an estimate of the disk space the HTTP cache is using, in bytes.
clearCache()Empties the HTTP cache. Cookies, local storage, and the other browsing data are left alone.
clearAuthCache()Forgets the credentials cached for HTTP authentication. Sites that asked for credentials ask again.
clearHostResolverCache()Empties the cache of resolved host names. Useful after the network or the DNS records change.
clearCodeCaches()Drops the compiled code cached for scripts and WebAssembly modules. They are compiled again on the next run.

For example, the following code empties the HTTP cache when it grows larger than 500 MB:

const bytes = await session.getCacheSize()
if (bytes > 500 * 1024 * 1024) {
  await session.clearCache()
}

Clearing code caches is useful when your application replaces scripts that its pages load from a custom scheme, where the usual HTTP cache validation doesn’t apply:

await session.clearCodeCaches({ urls: ['app://bundle/main.js'] })

User agent 

The userAgent property returns the user agent the session identifies itself with. To replace it, call setUserAgent():

console.log(session.userAgent)

session.setUserAgent('MyApp/1.0')

The new user agent is used by pages that are already open as well as by pages loaded afterwards. A page that has already loaded keeps reporting the previous value from navigator.userAgent until it navigates again.