在 JavaScript 中有清除网站数据的相当方法吗?

7

在这里输入图片描述

我想在Javascript函数中实现与“清除网站数据”相同的行为,因为我的Angular应用程序(在升级Angular后)似乎没有清除网站数据而出现问题,我不希望客户被迫自己清除网站数据。

如果无法清除所有内容,则是否至少有一种方法可以清除 1)localStorage、2)所有IndexedDB数据库、3)Cookies 和4)Web SQL?

先感谢你的帮助。


@Calvin,你找到清除网站数据的解决方案了吗? - DevD
@DevD 不幸的是,没有简单的解决方案。你可以稍微更改一下文件名,这样就不会使用浏览器缓存,循环遍历 localStorage 来删除所有项目等。但只有一个简单的内置函数来删除所有东西是不存在的。 - Calvin
1个回答

4
我创造了一个脚本来实现这个目标。在这里发布以便需要类似功能的人使用。
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();

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接