当 localStorage 满了时会发生什么?

我已经找到了关于高速缓存行为的 物品,所以我只能假设它没有太大的不同,但我想确保。

我读到大多数浏览器的 localStorage 都有5MB 的存储空间,我对这些浏览器的行为感兴趣?

我知道每个浏览器的表现都不一样,但我最感兴趣的还是 Safari、 Chrome 和 Firefox (我认为它们都是浏览器)。

  • 上面提到的浏览器会从我的网站上删除数据,还是会选择“最古老的”或类似的东西?
  • 在这种情况下,我的物品会被保存吗?

最重要的是:

  • 让我们说我“滥用”本地存储在我的网站上试图使用它的所有,在同一个页面,我填写它,并试图保存更多。我会得到警告吗?当这种情况发生时,getItem会返回 null吗? 还是以某种方式保存在内存中?

  • 如果我尝试保存一个大于 localStorage大小的项目会发生什么?

回答: 答案可以在这里找到

  • 是否可以期望 sessionStorage 具有相同的行为,而据称这些行为应该是相同的?

我知道这是一个很多问题,但我试图理解所有的相关主题,我会很感激任何部分的问题,你可以回答。

43851 次浏览

Firstly, some useful resources:

In answer to your question, desktop browsers tend to have an initial maximum localStorage quota of 5MB per domain. This can be adjusted by the user in some cases:

  • Opera: opera:config -> Domain Quota For localStorage
  • Firefox: about:config -> dom.storage.default_quota

In Chrome, there doesn't seem to be a way for the user to adjust this setting although like Opera, localStorage data can be edited directly per domain using the Developer Tools.

When you try to store data in localStorage, the browser checks whether there's enough remaining space for the current domain. If yes:

  • The data is stored, overwriting values if an identical key already exists.

If no:

  • The data is not stored and no existing data is overwritten.
  • A QUOTA_EXCEEDED_ERR exception is thrown.

In this case, getItem(key) will return the last value that was successfully stored, if any.

(Opera is slightly different in that it displays a dialog box giving the user the choice of increasing storage space for the current domain.)

Note that sessionStorage and localStorage are both implementations of the same Storage object so their behaviour is similar and error handling is the same.