首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何“安全”地使用window.history.pushState

如何“安全”地使用window.history.pushState
EN

Stack Overflow用户
提问于 2011-02-17 22:57:23
回答 3查看 40.9K关注 0票数 20

我想在支持浏览器时使用window.history.pushState()函数。不幸的是,我在Firefox上遇到一个错误:

TypeError: history.pushState不是函数

如何才能避免这种情况呢?

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2011-02-17 23:10:04

try-catch标签暗示了你已经知道的答案……(有没有更具体的东西?)另一种可能性是检查if ( history.pushState ) history.pushState( {}, document.title, location.href );

票数 19
EN

Stack Overflow用户

发布于 2011-03-30 02:40:15

尽管我没有在JavaScript中测试过它,但我知道在其他语言中,try-catch比简单的if...

使用:

代码语言:javascript
复制
if(history.pushState) {
    history.pushState({"id":100}, document.title, location.href);
}

请记住,当您单击back按钮时,除非实现window.onpopstate,否则不会发生任何实际情况。您需要传入获取内容所需的数据:

代码语言:javascript
复制
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
    };
}
票数 24
EN

Stack Overflow用户

发布于 2014-05-07 22:33:23

历史API确实存在填充程序。History.js使用HTML4的hashchange事件和文档片段标识符来模仿旧浏览器中的历史应用编程接口。如果现代浏览器使用其中一个散列URL,它会使用replaceState悄悄地更正该URL。

如果你不担心它不能在老的浏览器中工作,你只是想在不抛出错误的情况下使用它,我这样做...

代码语言:javascript
复制
window.history && window.history.pushState && window.history.pushState("", "", url);

这将在尝试使用历史记录和pushstate函数之前检查它是否存在。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/5030564

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档