且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

当 localStorage 已满时会发生什么?

更新时间:2022-06-15 01:02:32

首先,一些有用的资源:

Firstly, some useful resources:

在回答您的问题时,桌面浏览器的初始最大 localStorage 配额往往为每个域 5MB.在某些情况下,这可以由用户进行调整:

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 -> localStorage 的域配额
  • Firefox:about:config -> dom.storage.default_quota

在 Chrome 中,用户似乎没有办法调整此设置,尽管与 Opera 一样,可以使用开发者工具直接按域编辑 localStorage 数据.

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.

当您尝试在 localStorage 中存储数据时,浏览器会检查当前域是否有足够的剩余空间.如果是:

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

  • 存储数据,如果相同的键已存在,则覆盖值.

如果不是:

  • 不会存储数据,也不会覆盖现有数据.
  • 抛出一个 QUOTA_EXCEEDED_ERR 异常.

在这种情况下,getItem(key) 将返回最后成功存储的值(如果有).

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

(Opera 略有不同,它显示一个对话框,让用户可以选择增加当前域的存储空间.)

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

注意 sessionStorage 和 localStorage 都是同一个 Storage 对象的实现,所以它们的行为是相似的,错误处理是相同的.

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