2011-02-17 144 views

回答

18

[的try-catch]标签意味着你知道什么已经是答案......(有什么更具体的?) 其他possibitity是检查if (history.pushState) history.pushState({}, document.title, location.href);

23

虽然我没有在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 
    }; 
} 
+4

注意:history.popstate被调用一次 - 立即在首页加载:这是设计。 – 2012-12-10 22:10:12

0

Shim确实存在于历史记录API中。 History.js使用HTML4的hashchange事件和文档片段标识符来模拟旧版浏览器中的历史API。如果其中一个散列URL被现代浏览器使用,它将使用replaceState来悄悄地更正URL。

如果你不打扰它不是在旧的浏览器工作,你只是想用它而不发出一个错误,我做到这一点...

window.history && window.history.pushState && window.history.pushState("", "", url); 

这就验证了历史和pushState的功能在尝试使用它之前存在。

相关问题