是否可以阻止使用Safari桌面浏览器的客户端?

时间:2019-06-18 14:09:30

标签: javascript safari

因为Safari的桌面版本不支持<input type="date">,所以我想告诉使用Safari桌面版本的客户端应该切换到其他浏览器。

我尝试了以下功能,但不幸的是,即使使用Chrome,它也会返回Safari

function getBrowser() { 
    if((navigator.userAgent.indexOf("Opera") != -1 || navigator.userAgent.indexOf('OPR')) != -1 ) 
    {
        return 'Opera';
    }
    else if(navigator.userAgent.indexOf("Edge") != -1 )
    {
        return 'Edge';
    }
    else if(navigator.userAgent.indexOf("Samsung") != -1) {
        return 'Samsung Browser';
    }
    else if(navigator.userAgent.indexOf("Safari") != -1)
    {
        return 'Safari';
    }
    else if (navigator.userAgent.indexOf("Chrome") != -1) {
        return 'Chrome';
    }
    else if(navigator.userAgent.indexOf("Firefox") != -1 ) 
    {
        return 'Firefox';
    }
    else if(navigator.userAgent.indexOf("MSIE") != -1 )
    {
        return 'IE';
    }  
    else 
    {
        return 'unknown';
    }
}

还有另一种方法可以检测客户端是否正在使用Safari吗?如果有,是否有可能检测到正在使用其桌面版本的用户?因为在iPhone和iPad上<input type="date">标签可以正常工作。

2 个答案:

答案 0 :(得分:0)

在这种情况下,您不应该检查特定的浏览器类型。相反,您应该检查是否支持日期输入类型,如果不支持,请做出相应的反应。 https://diveinto.html5doctor.com/detect.html#input-types

基本方法是大多数浏览器将无法识别的输入类型转换为“文本”,因此您可以创建输入,将其类型设置为“日期”,然后查看是否已将其更改为“文本”:

const testInput = document.createElement('input');
testInput.setAttribute('type', 'date');
if (testInput.type !== 'date') {
    // The date input type is not supported by this browser.
}

答案 1 :(得分:0)

尝试这样查找浏览器名称。有关更多信息,请参阅此code

var objAgent = navigator.userAgent;
var objbrowserName  = navigator.appName;
var objOffsetName,objOffsetVersion;

// In Chrome 
if ((objOffsetVersion=objAgent.indexOf("Chrome"))!=-1) {
 objbrowserName = "Chrome";
}
// In Microsoft internet explorer
else if ((objOffsetVersion=objAgent.indexOf("MSIE"))!=-1) {
 objbrowserName = "Microsoft Internet Explorer";
}

// In Firefox
else if ((objOffsetVersion=objAgent.indexOf("Firefox"))!=-1) {
 objbrowserName = "Firefox";
}
// In Safari 
else if ((objOffsetVersion=objAgent.indexOf("Safari"))!=-1) {
 objbrowserName = "Safari";
}
// For other browser "name/version" is at the end of userAgent 
else if ( (objOffsetName=objAgent.lastIndexOf(' ')+1) < 
          (objOffsetVersion=objAgent.lastIndexOf('/')) ) 
{
 objbrowserName = objAgent.substring(objOffsetName,objOffsetVersion);
 if (objbrowserName.toLowerCase()==objbrowserName.toUpperCase()) {
  objbrowserName = navigator.appName;
 }
}

document.write('Browser name  = '+objbrowserName)