我想在支持浏览器时使用window.history.pushState()
函数。不幸的是,我在Firefox上遇到一个错误:
TypeError: history.pushState不是函数
如何才能避免这种情况呢?
发布于 2011-02-17 23:10:04
try-catch标签暗示了你已经知道的答案……(有没有更具体的东西?)另一种可能性是检查if ( history.pushState ) history.pushState( {}, document.title, location.href );
发布于 2011-03-30 02:40:15
尽管我没有在JavaScript中测试过它,但我知道在其他语言中,try-catch比简单的if...
使用:
if(history.pushState) {
history.pushState({"id":100}, document.title, location.href);
}
请记住,当您单击back按钮时,除非实现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
};
}
发布于 2014-05-07 22:33:23
历史API确实存在填充程序。History.js使用HTML4的hashchange事件和文档片段标识符来模仿旧浏览器中的历史应用编程接口。如果现代浏览器使用其中一个散列URL,它会使用replaceState悄悄地更正该URL。
如果你不担心它不能在老的浏览器中工作,你只是想在不抛出错误的情况下使用它,我这样做...
window.history && window.history.pushState && window.history.pushState("", "", url);
这将在尝试使用历史记录和pushstate函数之前检查它是否存在。
https://stackoverflow.com/questions/5030564
复制相似问题