如何确定浏览器是否支持js的pushState函数?

5
我想通过JavaScript脚本使用动态URL更新:
window.history.pushState("string", "Title", "/new-url");

但是,如果浏览器旧且不支持此函数,则应简单地重定向到新的URL。

有没有简单的方法来检查呢?


可能是重复的问题: https://dev59.com/7m445IYBdhLWcg3wQX2G - witherwind
4个回答

7
您只需检查:
if (history.pushState) {

}

5
try {
    window.history.pushState("string", "Title", "/new-url");
} catch ( e ) {
    window.location = "/new-url";
}

5
最简单(且性能最佳)的方法是:
if ('history' in window && 'pushState' in history) { // available

不过,我建议使用一些已经建立的历史记录管理解决方案,比如History.js


0
if(!!history && !!history.pushState){
   //browsers which support history and history's push state method
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接