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

How to determine if browser is supporting js pushState function?

本文关键字:js pushState 函数 支持 是否 何确定 浏览器      更新时间:2023-09-26

我想通过js脚本使用动态URL更新:

window.history.pushState("string", "Title", "/new-url");

但是,如果浏览器是旧的并且不支持此功能,它应该简单地重定向到新的URL。

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

您只需检查:

if (history.pushState) {
}

最简单(也是性能最高的):

if ('history' in window && 'pushState' in history) { // available

不过,我还是建议使用一些既定的历史记录管理解决方案,例如历史记录.js

try {
    window.history.pushState("string", "Title", "/new-url");
} catch ( e ) {
    window.location = "/new-url";
}
if(!!history && !!history.pushState){
   //browsers which support history and history's push state method
}