browser.tabs.onRemoved.addListener(tabId => {
// SNAFU: tabs.get() fails because the tabId is already considered ivalid
// But tabs.query() results still include the removed tab?
// Workaround: Determine the cookieStoreId of the removed tab by matching all tabs in the query and filtering for the id afterwards
browser.tabs.query({})
.then(tabs => browser.contextualIdentities.get(tabs.find(tab => tab.id == tabId).cookieStoreId))
.then(
identity => {
// Only clear containers following the naming convention
if (/\[private\]$/i.test(identity.name))
browser.tabs.query({ cookieStoreId: identity.cookieStoreId })
// This will include the removed tab!
.then(tabsUsingStore => {
if (tabsUsingStore.length <= 1) browser.browsingData.remove(
{ cookieStoreId: identity.cookieStoreId },
{
cookies: true,
indexedDB: true,
localStorage: true,
// The following will trigger an "Firefox does not support clearing X with 'cookieStoreId'." error
cache: false,
downloads: false,
formData: false,
history: false,
passwords: false,
pluginData: false,
serverBoundCertificates: false,
serviceWorkers: false
}
);
}
)
},
// The store was not associated with a contextual identity (i.e. the tab was not containerized)
error => {}
)
});