Cookies and storage
editCookies
Without a CookieJar, the pages have no cookies. Give the browsing contexts a jar: the document loader sends its cookies and stores the cookies of the responses, and the pages read and write it with document.cookie and cookieStore.
var cookies = new CookieJar();
cookies.SetCookie("https://example.com/", "session=abc; Path=/; Secure; HttpOnly");
cookies.SetCookie("https://example.com/", "theme=dark; Path=/");
using var context = new BrowsingContext(new BrowsingContextOptions { CookieJar = cookies });
var document = context.Navigate("https://example.com/", _ => "<p>Hello</p>");
// document.cookie does not see the HttpOnly cookies
Assert.Equal("theme=dark", document.Cookie);
document.Cookie = "lang=fr; Path=/";
var names = cookies.GetCookies("https://example.com/").Select(cookie => cookie.Name).Order(StringComparer.Ordinal);
Assert.Equal(["lang", "session", "theme"], names);- The jar follows the rules of the browsers (RFC 6265bis):
ExpiresandMax-Age,DomainandPath,Secure,HttpOnly,SameSite(Laxby default),Partitioned, the cookie prefixes and the public suffixes. Third-party cookies are not blocked by default (see Third-party cookies and storage access). - As in the browsers, the cookies of a host are shared by its schemes and its ports. Set OriginBound (
new CookieJar { OriginBound = true }) to bind them to the origin that set them (origin-bound cookies): a cookie set by anhttpspage is not sent to thehttppages of the same host, and the reverse, and a cookie withoutDomainattribute is only sent to the port that set it. The cookies of the same name set by another scheme or another port do not replace each other. StoredCookie.SourceScheme and SourcePort give the origin that set a cookie: persist them with the cookie, a cookie loaded without them is sent to every scheme and port. - Several browsing contexts can share a jar, as the tabs of a browser share their cookies.
SetCookie(url, header)adds a cookie as aSet-Cookieheader does (to sign a session in before loading a page);GetCookies(url)and GetCookies() list them, Remove and Clear delete them.- Create the jar with the
TimeProviderof the browsing context (new CookieJar(timeProvider)) so that the cookies expire with its clock. - To keep the persistent cookies between runs, derive from CookiePersistence (LoadCookies, SetCookie, RemoveCookie, ClearAll) and give it to the jar:
new CookieJar(persistence, timeProvider). The jar keeps the cookies in memory and reports each change.
Cookies in the service workers
A service worker reads and writes the cookies of its script URL with self.cookieStore (any URL of its origin with the url option). It does not get the change events of window.cookieStore: it subscribes to the changes with registration.cookies.subscribe([{ name, url }]), and receives a cookiechange event (ExtendableCookieChangeEvent) when a cookie that matches a subscription changes (the service worker is started if needed). A subscription matches the cookies of its name (any name when it has none) that are sent to its URL (the scope of the registration when it has none), which must be in the scope of the registration. The subscriptions belong to the registration: an update of the service worker keeps them, the ServiceWorkerBackend saves them with the registration (StoredServiceWorkerRegistration.CookieChangeSubscriptions), and unregistering drops them.
Third-party cookies and storage access
By default, as in the browsers that do not block them, a frame of another site than the top-level page sends and stores the cookies of its site. The default is deliberate: Safari blocks the third-party cookies, but Chrome keeps them, the cookie specification (RFC 6265bis) sends the SameSite=None cookies in the cross-site contexts, and many embedded pages (sign-in widgets, payment frames) need them. Set BlockThirdPartyCookies to block them, and SetThirdPartyCookieAccess to block or allow the cookies of a site in the pages of another site (the settings of the user):
var cookies = new CookieJar { BlockThirdPartyCookies = true };
cookies.SetCookie("https://embed.example/", "id=42; Path=/; Secure; SameSite=None");
// The request of an iframe of https://embed.example in a page of https://top.example
var request = new DocumentRequest("https://embed.example/widget")
{
CookieJar = cookies,
SiteForCookies = "https://top.example",
TopLevelOrigin = "https://top.example",
Origin = "https://top.example",
Destination = RequestDestination.Iframe,
};
Assert.Null(request.GetCookieHeader());
// Allow the cookies of https://embed.example in the pages of https://top.example
cookies.SetThirdPartyCookieAccess("https://top.example/", "https://embed.example/", blocked: false);
Assert.Equal("id=42", request.GetCookieHeader());- A context is third-party when its site is not the site of the top-level page, or when one of its parent frames is of another site. Its documents (
document.cookie,cookieStore) and its requests (subresources,fetch(), WebSockets, the navigations of its frames) neither see nor set the unpartitioned cookies of a blocked site:document.cookieignores them, andcookieStore.set()rejects its promise with aTypeError. The cookies with thePartitionedattribute are not blocked: they are kept per top-level site. - SetThirdPartyCookieAccess takes null for every top-level site or every embedded site. The rule of a pair of sites wins over the rule of every embedded site, which wins over the rule of every top-level site, which wins over BlockThirdPartyCookies.
A blocked frame gets its cookies back with the Storage Access API, from its scripts or from .NET (Document.HasStorageAccess and Document.RequestStorageAccess):
document.requestStorageAccess()is granted when thestorage-accesspermission is granted, or when the frame has a user activation (a click) and RequestPermission grants it. The permission is kept by Permissions for the pair of the sites of the top-level page and of the frame. It is always granted in a top-level page, in a frame of the top-level site, and for a site whose cookies are allowed; it is rejected in a page that is not secure (https), that is sandboxed withoutallow-storage-access-by-user-activation, that is loaded in a credentialless iframe, or whosestorage-accesspermissions policy is disabled (<iframe allow="storage-access 'none'">).- Once granted, the frame has storage access: its scripts see the cookies, and so do its requests to its own origin. The requests to other origins, the requests of the workers it starts and the other frames of the site do not. A reload of the frame, or a navigation that the frame starts to its own origin, keeps the access; a navigation started by another frame does not.
document.hasStorageAccess()tells whether the frame has access to its cookies: always true in a first-party context and for a site whose cookies are not blocked.- The requests from a third-party context send the
Sec-Fetch-Storage-Accessheader (Storage Access Headers):activewhen the cookies are sent,inactivewhen the permission is granted but the request does not use it,noneotherwise. A response withActivate-Storage-Access: retry; allowed-origin="..."makes aninactiverequest be sent again with the cookies, and the document of a frame whose response hasActivate-Storage-Access: loadgets storage access.
The other storages of a frame
The other storages of a frame of another site than the top-level page are partitioned by the top-level site: its localStorage, sessionStorage, IndexedDB databases, caches, origin private file system, locks, broadcast channels and shared workers are not the ones its site gets as a top-level page. document.requestStorageAccess(types) (Extending Storage Access API to non-cookie storage, or Document.RequestStorageAccess from .NET) is granted as document.requestStorageAccess() and returns a StorageAccessHandle whose members give the unpartitioned storages:
// A frame of https://other.example in a page of another site: window.localStorage is partitioned by the top-level site
frame.DefaultView!.LocalStorage.SetItem("partitioned", "1");
// The handle gives the storage of https://other.example when it is not embedded by another site
var request = frame.RequestStorageAccess(new StorageAccessTypes { LocalStorage = true, IndexedDB = true });
context.EventLoop.RunUntilIdle();
var handle = await request;
handle.LocalStorage.SetItem("unpartitioned", "2");
Assert.Null(handle.LocalStorage.GetItem("partitioned"));
Assert.Null(frame.DefaultView.LocalStorage.GetItem("unpartitioned"));
// The members that were not requested throw an InvalidStateError
Assert.Equal("InvalidStateError", Assert.Throws<DomException>(() => handle.SessionStorage).Name);- The StorageAccessTypes select the members that can be used (
allfor every member); a request without any type is rejected with anInvalidStateError. The frame gets its unpartitioned cookies only whenallorcookiesis requested.document.hasUnpartitionedCookieAccess()isdocument.hasStorageAccess(). - A
storageevent of an area of a handle is fired at the window of the frame, with the handle'sStorageobject asstorageArea. createObjectURL()andrevokeObjectURL()of a handle create and revoke the blob URLs of the first-party contexts of the origin. A frame that has storage access, of the top-level site but embedded by a frame of another site, can fetch the blob URLs of the first-party contexts; it revokes them only through the handle. ThesameSiteCookiesoption of the shared workers is not implemented.
Local storage and session storage
window.localStorage keeps its items in a StorageShed. By default, each browsing context created by your application has its own; give the same shed to several browsing contexts to share the items of an origin:
// The local storage areas of the origins, which several browsing contexts can share
var storage = new StorageShed();
using var context = new BrowsingContext(new BrowsingContextOptions { LocalStorage = storage });
context.Navigate("https://example.com/", _ => "<p>Hello</p>");
// window.localStorage, from .NET or from the scripts of the page
context.Window.LocalStorage.SetItem("theme", "dark");
Assert.Equal([new("theme", "dark")], storage.GetItems("https://example.com"));- The items are kept per origin, with a quota of 5 Mi characters per origin (
new StorageShed(quota)sets another one). GetOrigins, GetItems, SetItem and Clear read and change them from .NET. - To keep the items between runs, derive from WebStoragePersistence and give it to the shed:
new StorageShed(persistence). window.sessionStoragebelongs to the top-level browsing context, and is always kept in memory.
Storage partitioning
As in the browsers, the storage of a page embedded by another site is partitioned by the site of the top-level page (storage partitioning): an https://embed.example frame in a page of https://top.example does not see the local storage, the session storage, the IndexedDB databases, the caches, the origin private file system, the BroadcastChannel messages and the service workers of https://embed.example when it is the top-level page, nor the ones of the frames of https://embed.example in the pages of another site. The storage of a frame of the top-level site whose parent frame is of another site is partitioned too.
The blob URLs are partitioned the same way (FileAPI): a document or a worker of another partition cannot fetch nor revoke a URL created by URL.createObjectURL() (a frame navigated to it gets a network error), except for a top-level navigation. A link or window.open() opens a blob URL whose origin is not same site with the top-level page without opener.
- StorageShed.GetItems, SetItem and GetOrigins only give the items of the top-level pages (the first-party storage).
- The partitioned items of the local storage, and the partitioned service worker registrations, are kept in memory: they are not given to the persistence.
- The backends of the other stores receive the storage key of a partition in place of the origin: the origin, the site of the top-level page and whether a parent frame is of another site, separated by
^(https://embed.example^https://top.example^0).
The other stores
The other storage APIs of the browsers keep their data in backends that you can replace, to share or persist them:
| Option | Store | Default |
|---|---|---|
| IndexedDB | indexedDB | InMemoryIndexedDBBackend, per browsing context created by the application |
| CacheStorage | caches (the Cache API) | In memory |
| FileSystem | The origin private file system (navigator.storage.getDirectory()) | In memory |
| ServiceWorkers | The registrations of the service workers | In memory |
These stores are used by the scripts of the pages: they need a script engine.
Storage buckets
navigator.storageBuckets (Storage Buckets, Navigator.StorageBuckets from .NET) creates named buckets of the origin. A StorageBucket has its own IndexedDB databases, caches and origin private file system, kept in the same stores as the ones of the origin, but apart from them:
// A bucket has its own databases, caches and file system, apart from the ones of the origin
var drafts = await Run(buckets.Open("drafts", new StorageBucketOptions { Quota = 1_000_000 }));
var root = await Run(drafts.GetDirectory());
await Run(root.GetFileHandle("draft.txt", new FileSystemGetFileOptions { Create = true }));
var originRoot = await Run(document.DefaultView!.Navigator.Storage.GetDirectory());
await Assert.ThrowsAsync<DomException>(() => Run(originRoot.GetFileHandle("draft.txt")));
Assert.Equal(1_000_000ul, (await Run(drafts.Estimate())).Quota);
Assert.Equal(["drafts"], await Run(buckets.Keys()));
// Deleting the bucket deletes its storage: its objects then fail with an UnknownError
await Run(buckets.Delete("drafts"));
Assert.Empty(await Run(buckets.Keys()));
Assert.Equal("UnknownError", (await Assert.ThrowsAsync<DomException>(() => Run(drafts.Persisted()))).Name);- A bucket name has 1 to 64 lowercase ASCII letters, digits,
-and_, and starts with a letter or a digit. - The buckets of an origin are stored with their data, in the backends of BrowsingContextOptions.IndexedDB, CacheStorage and FileSystem, in the partition of the page (the buckets of a frame of another site are not the ones of its site as a top-level page). With the default in-memory backends, they are shared by the pages and the workers of a browser tab and the tabs it opens. Browser tabs that share a backend, or that use a persistent backend again, see the same buckets, whatever the order in which they open them. Each backend stores the buckets in a namespace of its own: the storage key prefixed by
storage-buckets, as empty databases, caches and directories named after the bucket, the order of its creation and a GUID, and a tombstone for its latest deletion. When the backends disagree (a backend that a browser tab did not use when it deleted or created a bucket), the latest creation or deletion wins: a deleted bucket stays deleted, and the storage of a bucket is only removed when it is deleted (bydelete(), its expiration orClear-Site-Data), not when a backend has an older copy of it. The quota and the expiration time of a bucket are only known by the browser tab that opened it. persist()asks StorageOptions.RequestPersistentStorage, asnavigator.storage.persist().estimate()reports the usage of the bucket and its quota (thequotaoption, or the quota of the origin). The quota of a bucket limits its file system, not its databases nor its caches.- A bucket whose
expirestime is past is deleted the next time the buckets are opened or listed. Deleting a bucket deletes its caches, its file system and its databases that no page keeps open.
Clear-Site-Data
A site clears the data that the browser keeps for it with the Clear-Site-Data header of a response. The header is honored on the responses of the secure URLs (https, and http://localhost), when the request sends credentials:
| Type | What is cleared for the origin of the response |
|---|---|
"cache" | The responses of its URLs in the HTTP cache and its pages in the back/forward cache (for the tab's site only, as the browsers partition their caches), and its prefetched and prerendered pages |
"cookies" | The cookies of its registrable domain ("cookies" for https://www.example.com removes the cookies of example.com and of its subdomains) |
"storage" | Its local storage, its session storage, its IndexedDB databases, its caches of the Cache API, its storage buckets, and its service worker registrations |
"executionContexts" | Its pages are reloaded |
"clientHints" | The client hints it opted into (also cleared by "cache" and "cookies") |
"*" | All of the above |
The header is also honored on the responses of the background revalidations of the HTTP cache (the responses used within their stale-while-revalidate window), and a response that clears the cache is not stored in it.
The cookies that the response sets are cleared too. As in the browsers, a response loaded by a page of another site (a third-party resource or frame) only clears the data of that page's partition: the partitioned cookies, the caches, and the stores of the origin partitioned by the site of that page. The stores of the origin as a top-level page are kept. So are they for a response loaded by a frame of the top-level site whose parent frame is of another site: it clears the stores of that frame's partition. A response loaded by a credentialless iframe only clears the stores of the credentialless iframes of its page (their storage is kept apart from the storage of the origin).
As in Chromium, the service worker registrations of the origin are cleared at once, without waiting for their pages to unload: their workers are terminated (their state becomes redundant), the requests whose fetch event waits for its respondWith() promise fail, and the pages they control lose their controller (navigator.serviceWorker.controller is null after a controllerchange event). A registration that unregister() already removed, but that still controls a page, is cleared too.
Some data is always kept:
- An IndexedDB database that a page still has open.
- The origin private file system.
"executionContexts"only reloads the pages in the tab of the request, and never the page or frame that loaded the response, nor the pages that contain it: reloading them would load the response again, forever.