检查浏览器兼容性是否支持HTML5历史API

Check browser compatibility for HTML5 History API support?

本文关键字:HTML5 历史 API 支持 是否 浏览器 兼容性 检查      更新时间:2023-09-26

是否有任何方法可以检查浏览器是否支持使用JavaScript的"HTML5 History API"。

我必须用if语句中的一长串条件来检查所有浏览器及其版本吗。或者简单地像检查函数的任何对象一样使用"if"语句就足够了???。。。

检查全局历史对象上是否存在pushState()方法就足够了。

function supports_history_api() {
  return !!(window.history && history.pushState);
}

对于更通用的HTML5功能检测,我会查看Modernizer

http://diveintohtml5.info/detect.html#modernizr

这将使您的代码与每个测试的混乱细节隔离开来,使代码更可读,更不容易出错。在你的页面上有Modernizer脚本,你只需要做:

if (Modernizr.history) {
  // history management works!
} else {
  // no history support :(
  // fall back to a scripted solution like History.js
}

检查history.pushStatehistory.replaceState对象的存在应该是足够的,因为它通常对于特征检测来说是足够的。

您可以使用canuse.js脚本来检测浏览器是否支持历史记录

caniuse.history()

您可以检查功能是否注册:

if (typeof history.pushState != 'undefined') {
    //Enabled
}

然后只需将//Enabled替换为您希望执行的任何操作(如果支持的话)。