17

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

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

4

4 回答 4

18

规范没有设置限制,但是各种浏览器确实有自己的限制。

Firefox 的文档有据可查,正如您所说,它是 640kB(“任何人都需要的内存”)。

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

Chrome 至少可以工作到 10MB(可能更多),

IE 达到了 1MB 的限制(在 IE11 中,这是我所拥有的一切)。

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

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

于 2014-03-06T03:12:08.717 回答
9

不。这里的规范性文件是http://www.whatwg.org/specs/web-apps/current-work/multipage/history.html#dom-history-pushstate它甚至没有提到数据的限制尺寸。但是,建议使用不同的限制:

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

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

于 2011-06-24T01:00:19.547 回答
0

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

于 2013-04-03T07:52:39.993 回答
0

煞费苦心地,我有一个页面超过了 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;
}

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

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);
            }
         });
    }
});
于 2018-07-26T23:38:17.657 回答