Calvin
Calvin

Reputation: 377

Clear site data equivalent in Javascript?

enter image description here

I want to have the same behavior as 'Clear site data' in a Javascript function, because my Angular app (after upgrading Angular) seems to misbehave without clearing site data and I don't want customers to be forced to clear site data themselves.

If it's not possible to clean everything, is there at least a way to clean 1) localStorage 2) all IndexedDB databases 3) Cookies and 4) Web SQL

Thanks in advance

Upvotes: 7

Views: 1867

Answers (1)

DevD
DevD

Reputation: 364

I created a script to achieve this. Posting here in case anyone needs something similar.

var theCookies = document.cookie.split(';');
for (var i = 1 ; i <= theCookies.length; i++) {
    var acookie = theCookies[i-1];
    var cookieArr = acookie.split('=');
    console.log(cookieArr[0]);
    document.cookie = cookieArr[0]+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;";
}

// Get cache storage and clear cache storage
window.caches.keys().then(function(names) {
    for (let name of names)
        window.caches.delete(name);
});

// Get indexed db and delete indexed db
const dbs = await window.indexedDB.databases()
dbs.forEach(db => { window.indexedDB.deleteDatabase(db.name) })

// clear localStorage
window.localStorage.clear();

// clear sessionStorage
window.sessionStorage.clear();

Upvotes: 4

Related Questions