HTML5历史API-状态对象的最大大小是多少

HTML5 History API - What is the max size the state object can be?

本文关键字:多少 历史 API- 状态 对象 HTML5      更新时间:2023-09-26

pushState方法接受一个状态对象。Firefox文档中说,这个对象的最大大小是640kb。规格中是否定义了浏览器可以实现的最小最大大小?我能合理地期望主流浏览器为我提供至少100kb的容量吗?

编辑:我用Chrome进行了测试,它仍然适用于1MB以上的状态对象。

规范没有规定限制,但各种浏览器都有自己的限制。

Firefox有很好的文档记录,正如你所说,它是640kB("任何人都需要的RAM")。

我在任何地方都找不到Chrome或Internet Explorer的列表,但一些快速测试显示:

Chrome至少可工作10MB(可能更高),

IE达到1MB的极限(在IE11中,这是我手头的全部)。

因此,为未来的人们总结一下:history.state对象大小限制为:对于Firefox为640kB,对于Internet Explorer 11为1MB,对于Chrome为至少10Mb

编辑:测试版本:IE:11,Chrome:33,Firefox:无关,因为它们为您记录了MDN的最大大小:)。

否。此处的规范性文件为http://www.whatwg.org/specs/web-apps/current-work/multipage/history.html#dom-历史推送状态,甚至没有提到数据大小的限制。然而,建议使用不同的限制:

用户代理可以限制添加到会话的状态对象每页的历史记录。

正如你在这个例子中看到的,规范通常避免提及任何硬限制,并将其留给浏览器制造商自行决定。因此,即使在未来的某个时候修改规范以考虑数据大小限制的可能性,它也不太可能给你一个真实的数字。相反,它将"足够大,可以用于常见的用例"。

只看到MDN,告诉FireFox将大小限制在640K,不知道其他浏览器。https://developer.mozilla.org/en-US/docs/DOM/Manipulating_the_browser_history

令人痛苦的是,我有一个页面超过了IE11上的字符限制。由于在任何地方都找不到,我做了一个子字符串操作来获得确切的字符数。答案是(至少在IE11上)允许524282个字符传递到pushState/replaceState
我通过以下代码处理了这个问题:

function pushState(data, title, url) {
  if (data.length > 524282) {
      //can't push the data to the History API--pass null
      history.pushState(null, title, url);
      history.replaceState(null, title, url);
  }
  else {
    history.pushState(data, title, url);
    history.replaceState(data, title, url);
  }
    document.title = title;
}

我调用beforeAvigate来保存用户在通过ajax请求加载新内容之前所做的任何当前位置信息或状态更改。

function beforeNavigate(){
    if ($("#container").html().length <= 524282) {
        //save current state to history before navigating via ajax
        history.replaceState($("#container").html(), document.title, window.location.pathname);
    }
}

通过监听popstate来处理按下后退和前进按钮。如果我们为数据传递了一个null值,那么e.state将返回null,我们需要通过ajax请求加载存储的url。

window.addEventListener('popstate', function (e) {
    if (e.state!=null) {
        $("#container").html(e.state);
    }
    else {
        //load the partialpage into the container(a full html page is not returned by the ajax query for my site)
        $.ajax({
            url: location.href,
            type: "GET",
            success: function (data) {
                $('#container').html(data);
            }
         });
    }
});

Firefox现在对history.state施加了16MiB的限制:https://developer.mozilla.org/en-US/docs/Web/API/History/pushState#parameters

Chrome和其他浏览器仍然没有记录这一点,请参阅其他答案了解详细信息。