我想在支持浏览器中使用window.history.pushState()
函数。不幸的是我在Firefox上遇到了一个错误:如何安全地使用window.history.pushState
TypeError: history.pushState is not a function
怎么可能避免这种情况?
我想在支持浏览器中使用window.history.pushState()
函数。不幸的是我在Firefox上遇到了一个错误:如何安全地使用window.history.pushState
TypeError: history.pushState is not a function
怎么可能避免这种情况?
[的try-catch]标签意味着你知道什么已经是答案......(有什么更具体的?) 其他possibitity是检查if (history.pushState) history.pushState({}, document.title, location.href);
虽然我没有在JavaScript测试它,我知道在的try-catch更多的资源不是一个简单的,如果密集其他语言...
用途:
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
};
}
Shim确实存在于历史记录API中。 History.js使用HTML4的hashchange事件和文档片段标识符来模拟旧版浏览器中的历史API。如果其中一个散列URL被现代浏览器使用,它将使用replaceState来悄悄地更正URL。
如果你不打扰它不是在旧的浏览器工作,你只是想用它而不发出一个错误,我做到这一点...
window.history && window.history.pushState && window.history.pushState("", "", url);
这就验证了历史和pushState的功能在尝试使用它之前存在。
注意:history.popstate被调用一次 - 立即在首页加载:这是设计。 – 2012-12-10 22:10:12