【发布时间】:2011-06-29 04:04:44
【问题描述】:
我想在支持的浏览器中使用window.history.pushState() 功能。不幸的是,我在 Firefox 上遇到错误:
TypeError:history.pushState 不是函数
如何避免这种情况?
【问题讨论】:
标签: javascript html try-catch
我想在支持的浏览器中使用window.history.pushState() 功能。不幸的是,我在 Firefox 上遇到错误:
TypeError:history.pushState 不是函数
如何避免这种情况?
【问题讨论】:
标签: javascript html try-catch
History API 确实存在垫片。 History.js 使用 HTML4 的 hashchange 事件和文档片段标识符来模仿旧浏览器中的历史 API。如果现代浏览器使用其中一个哈希 URL,它会使用 replaceState 悄悄地更正 URL。
如果您不担心它无法在旧版浏览器中运行,并且只想使用它而不会引发错误,我会这样做...
window.history && window.history.pushState && window.history.pushState("", "", url);
这会在尝试使用之前检查历史记录和 pushstate 函数是否存在。
【讨论】:
虽然我没有在 JavaScript 中测试过它,但我知道在其他语言中 try-catch 比简单的 if... 更耗费资源......
用途:
if(history.pushState) {
history.pushState({"id":100}, document.title, location.href);
}
请记住,当您单击后退按钮时,除非您实现 window.onpopstate,否则实际上什么都不会发生。您需要传入获取内容所需的数据:
if(history.pushState && history.replaceState) {
//push current id, title and url
history.pushState({"id":100}, document.title, location.href);
//push new information
history.pushState({"id":101}, "new title", "/new-url/");
//this executes when you use the back button
window.onpopstate = function(e) {
alert(e.state.id);
//perhaps use an ajax call to update content based on the e.state.id
};
}
【讨论】:
[try-catch] 标签暗示了你已经知道的答案......(有什么更具体的吗?)
另一种可能性是检查if ( history.pushState ) history.pushState( {}, document.title, location.href );
【讨论】: