JS 判断当前浏览器是谷歌Google、火狐Firefox、Safari、Edge、Opera还是其他浏览器的方法

文章提供了两种JavaScript方法来检测用户正在使用的浏览器类型,包括GoogleChrome、Firefox、Safari和Edge。第一种方法是通过比较navigator.userAgent字符串中的特定字符串来判断。第二种方法使用正则表达式匹配用户代理字符串,分别提取Edge、Firefox、Chrome和Safari的信息。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

JS 判断当前浏览器是谷歌Google、火狐Firefox、Safari、Edge还是其他浏览器的方法,如下:

第一种:

function detectBrowser() {
    const userAgent = navigator.userAgent;
    if (userAgent.indexOf("Chrome")!== -1 && userAgent.indexOf("Safari") !== -1 && userAgent.indexOf("Edg") === -1) {
      return "Google Chrome"; // Chrome
    } else if (userAgent.indexOf("Firefox") !== -1) {
      return "Mozilla Firefox"; // Firefox
    } else if (userAgent.indexOf("Safari") !== -1 && userAgent.indexOf("Chrome") === -1 && userAgent.indexOf("Edge") === -1) {
      return "Apple Safari"; // Safari
    } else if (userAgent.indexOf("Edg") !== -1) {
      return "Microsoft Edge"; // Edge
    } else {
      return "Unknown browser"; // 其他浏览器...(可根据自己需要确定是否新增其他浏览器的判断)
    }
}

第二种:

let SystemFlag = {};
let uaFlag = navigator.userAgent.toLowerCase();
let uaFlagMatch;
(uaFlagMatch = uaFlag.match(/edg\/([\d.]+)/))
  ? (SystemFlag.edg = uaFlagMatch[1])
  : (uaFlagMatch = uaFlag.match(/firefox\/([\d.]+)/))
  ? (SystemFlag.firefox = uaFlagMatch[1])
  : (uaFlagMatch = uaFlag.match(/chrome\/([\d.]+)/))
  ? (SystemFlag.chrome = uaFlagMatch[1])
  : (uaFlagMatch = uaFlag.match(/opera.([\d.]+)/))
  ? (SystemFlag.opera = uaFlagMatch[1])
  : (uaFlagMatch = uaFlag.match(/version\/([\d.]+).*safari/))
  ? (SystemFlag.safari = uaFlagMatch[1])
  : 0;
// Edge
if (SystemFlag.edg) document.write("Edge: " + SystemFlag.edg);
// Firefox
if (SystemFlag.firefox) document.write("Firefox: " + SystemFlag.firefox);
// Chrome
if (SystemFlag.chrome) document.write("Chrome: " + SystemFlag.chrome);
// Opera
if (SystemFlag.opera) document.write("Opera: " + SystemFlag.opera);
// Safari
if (SystemFlag.safari) document.write("Safari: " + SystemFlag.safari);

评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值