检测 Safari 浏览器

发布于 2024-12-12 17:09:19 字数 231 浏览 5 评论 0原文

如何使用 JavaScript 检测 Safari 浏览器?我尝试过下面的代码,它不仅可以检测 Safari,还可以检测 Chrome 浏览器。

function IsSafari() {

  var is_safari = navigator.userAgent.toLowerCase().indexOf('safari/') > -1;
  return is_safari;

}

How to detect Safari browser using JavaScript? I have tried code below and it detects not only Safari but also Chrome browser.

function IsSafari() {

  var is_safari = navigator.userAgent.toLowerCase().indexOf('safari/') > -1;
  return is_safari;

}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(25

箜明 2024-12-19 17:09:21

我测试了 #Christopher Martin 发布的代码,它将我的浏览器报告为 Chrome,因为它在测试 Edge 之前对此进行了测试,否则 Edge 会回答用于识别 Chrome 的测试。我修改了他的答案以纠正这个缺陷和另外两个缺陷,即:

  1. Edge 的缩写用户代理子字符串
  2. MSIE 的非常旧的字符串

将代码转换为函数会产生以下函数和测试脚本,通过调试控制台进行报告。

    <script type="text/javascript">
    function BasicBrowserSniffer ( )
    {
        if ( navigator.userAgent.match ( /edge\//i ) ) {
            return 'edge/edgehtml';
        }
        if ( navigator.userAgent.match ( /edg\//i ) ) {
            return 'edge/edgehtml';
        }
        else if ( navigator.vendor.match ( /google/i ) ) {
            return 'chrome/blink';
        }
        else if ( navigator.vendor.match ( /apple/i ) ) {
            return 'safari/webkit';
        }
        else if ( navigator.userAgent.match ( /firefox\//i ) ) {
            return 'firefox/gecko';
        }
        else if ( navigator.userAgent.match ( /trident\//i ) ) {
            return 'ie/trident';
        }
        else if ( navigator.userAgent.match ( /msie\//i ) ) {
            return 'ie/trident';
        }
        else
        {
            return navigator.userAgent + "\n" + navigator.vendor;
        }
    };  // BasicBrowserSniffer function

    console.info ( 'Entering function anonymous DocumentReady function' );
    console.info ( 'User Agent String   = ' + navigator.userAgent.toLowerCase ( ));
    console.info ( 'User Agent Vendor   = ' + var uav = navigator.vendor.toLowerCase ( );
    console.info ( 'BasicBrowserSniffer = ' + BasicBrowserSniffer ( ) );
    console.info ( 'Leaving function anonymous DocumentReady function' );
</script>

I tested the code posted by #Christopher Martin, and it reported my browser as Chrome, because it tests for that before testing for Edge, which would otherwise answer true to the test that is intended to identify Chrome. I amended his answer to correct that deficiency and two others, namely:

  1. The abbreviated user agent substring for Edge
  2. The very old string for MSIE

Converting the code into a function yields the following function and test script that reports via the debug console.

    <script type="text/javascript">
    function BasicBrowserSniffer ( )
    {
        if ( navigator.userAgent.match ( /edge\//i ) ) {
            return 'edge/edgehtml';
        }
        if ( navigator.userAgent.match ( /edg\//i ) ) {
            return 'edge/edgehtml';
        }
        else if ( navigator.vendor.match ( /google/i ) ) {
            return 'chrome/blink';
        }
        else if ( navigator.vendor.match ( /apple/i ) ) {
            return 'safari/webkit';
        }
        else if ( navigator.userAgent.match ( /firefox\//i ) ) {
            return 'firefox/gecko';
        }
        else if ( navigator.userAgent.match ( /trident\//i ) ) {
            return 'ie/trident';
        }
        else if ( navigator.userAgent.match ( /msie\//i ) ) {
            return 'ie/trident';
        }
        else
        {
            return navigator.userAgent + "\n" + navigator.vendor;
        }
    };  // BasicBrowserSniffer function

    console.info ( 'Entering function anonymous DocumentReady function' );
    console.info ( 'User Agent String   = ' + navigator.userAgent.toLowerCase ( ));
    console.info ( 'User Agent Vendor   = ' + var uav = navigator.vendor.toLowerCase ( );
    console.info ( 'BasicBrowserSniffer = ' + BasicBrowserSniffer ( ) );
    console.info ( 'Leaving function anonymous DocumentReady function' );
</script>
愛上了 2024-12-19 17:09:21

基于@SudarP 的回答。

到 2021 年第 3 季度,此解决方案将在 Firefox (Uncaught TypeError: navigator.vendor.match(...) is null) 和 Chrome (Uncaught TypeError: Cannot read properties of null (reading)) 中失败'长度'));

所以这是一个固定且更短的解决方案:

function isSafari() {
  return (navigator.vendor.match(/apple/i) || "").length > 0
}

Based on @SudarP answer.

At Q3 2021 this solution will fail in either Firefox (Uncaught TypeError: navigator.vendor.match(...) is null) and Chrome (Uncaught TypeError: Cannot read properties of null (reading 'length'));

So here is a fixed and shorter solution:

function isSafari() {
  return (navigator.vendor.match(/apple/i) || "").length > 0
}
七度光 2024-12-19 17:09:21

此代码仅用于检测safari浏览器

const isSafari = /^((?!chrome|android).)*safari/i.test(navigator.userAgent)

This code is used to detect only safari browser

const isSafari = /^((?!chrome|android).)*safari/i.test(navigator.userAgent)
海未深 2024-12-19 17:09:21

我创建一个返回布尔类型的函数:

export const isSafari = () => navigator.userAgent.toLowerCase().indexOf('safari') !== -1

I create a function that return boolean type:

export const isSafari = () => navigator.userAgent.toLowerCase().indexOf('safari') !== -1
榕城若虚 2024-12-19 17:09:21

用户代理嗅探确实很棘手且不可靠。我们试图用类似上面 @qingu 的答案来检测 iOS 上的 Safari,它对于 Safari、Chrome 和 Firefox 确实工作得很好。但它错误地将 Opera 和 Edge 检测为 Safari。

因此我们采用了功能检测,从目前来看,serviceWorker 仅在 Safari 中受支持,iOS 上的任何其他浏览器均不支持。如 https://jakearchibald.github.io/isserviceworkerready/ 中所述

支持不包括该平台上第三方浏览器的 iOS 版本(请参阅 Safari 支持)。

所以我们做了类似

if ('serviceWorker' in navigator) {
    return 'Safari';
}
else {
    return 'Other Browser';
}

注意的事情:未在 MacOS 上的 Safari 上进行测试。

User agent sniffing is really tricky and unreliable. We were trying to detect Safari on iOS with something like @qingu's answer above, it did work pretty well for Safari, Chrome and Firefox. But it falsely detected Opera and Edge as Safari.

So we went with feature detection, as it looks like as of today, serviceWorker is only supported in Safari and not in any other browser on iOS. As stated in https://jakearchibald.github.io/isserviceworkerready/

Support does not include iOS versions of third-party browsers on that platform (see Safari support).

So we did something like

if ('serviceWorker' in navigator) {
    return 'Safari';
}
else {
    return 'Other Browser';
}

Note: Not tested on Safari on MacOS.

尤怨 2024-12-19 17:09:20

注意:始终尝试检测您要修复的特定行为,而不是使用 isSafari?

作为目标,作为最后的手段,检测具有此正则表达式的 Safari:

var isSafari = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);

它使用负查找,并且排除 Chrome、Edge 以及所有包含 <代码>Safari他们的用户代理中的名称。

Note: always try to detect the specific behavior you're trying to fix, instead of targeting it with isSafari?

As a last resort, detect Safari with this regex:

var isSafari = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);

It uses negative look-arounds and it excludes Chrome, Edge, and all Android browsers that include the Safari name in their user agent.

旧竹 2024-12-19 17:09:20

正如其他人已经指出的那样,功能检测优于检查特定浏览器。原因之一是用户代理字符串可以更改。另一个原因是该字符串可能会更改并破坏较新版本中的代码。

如果您仍然想这样做并测试任何 Safari 版本,我建议使用此方法,

var isSafari = navigator.vendor && navigator.vendor.indexOf('Apple') > -1 &&
               navigator.userAgent &&
               navigator.userAgent.indexOf('CriOS') == -1 &&
               navigator.userAgent.indexOf('FxiOS') == -1;

这适用于所有设备上的任何版本的 Safari:Mac、iPhone、iPod、iPad。

编辑

要在当前浏览器中进行测试: https://jsfiddle.net/j5hgcbm2/

编辑 2

根据 < a href="https://developer.chrome.com/multidevice/user-agent" rel="noreferrer">Chrome 文档,用于正确检测 iOS 上的 Chrome

值得注意的是,iOS 上的所有浏览器都是只是 Safari 的包装并使用相同的引擎。请参阅 bfred.it 在该线程中对他自己的答案的评论。

编辑3

根据Firefox 文档更新正确检测 iOS 上的 Firefox

As other people have already noted, feature detection is preferred over checking for a specific browser. One reason is that the user agent string can be altered. Another reason is that the string may change and break your code in newer versions.

If you still want to do it and test for any Safari version, I'd suggest using this

var isSafari = navigator.vendor && navigator.vendor.indexOf('Apple') > -1 &&
               navigator.userAgent &&
               navigator.userAgent.indexOf('CriOS') == -1 &&
               navigator.userAgent.indexOf('FxiOS') == -1;

This will work with any version of Safari across all devices: Mac, iPhone, iPod, iPad.

Edit

To test in your current browser: https://jsfiddle.net/j5hgcbm2/

Edit 2

Updated according to Chrome docs to detect Chrome on iOS correctly

It's worth noting that all Browsers on iOS are just wrappers for Safari and use the same engine. See bfred.it's comment on his own answer in this thread.

Edit 3

Updated according to Firefox docs to detect Firefox on iOS correctly

江挽川 2024-12-19 17:09:20

只需使用:

var isSafari = window.safari !== undefined;
if (isSafari) console.log("Safari, yeah!");

请注意,这对于移动版本的 Safari 可能不可靠。

Just use:

var isSafari = window.safari !== undefined;
if (isSafari) console.log("Safari, yeah!");

Note this might not be reliable for mobile versions of Safari.

茶色山野 2024-12-19 17:09:20

您可以轻松地使用 Chrome 的索引来过滤掉 Chrome:

var ua = navigator.userAgent.toLowerCase(); 
if (ua.indexOf('safari') != -1) { 
  if (ua.indexOf('chrome') > -1) {
    alert("1") // Chrome
  } else {
    alert("2") // Safari
  }
}

You can easily use index of Chrome to filter out Chrome:

var ua = navigator.userAgent.toLowerCase(); 
if (ua.indexOf('safari') != -1) { 
  if (ua.indexOf('chrome') > -1) {
    alert("1") // Chrome
  } else {
    alert("2") // Safari
  }
}
嗫嚅 2024-12-19 17:09:20

此代码仅用于检测safari浏览器

if (navigator.userAgent.search("Safari") >= 0 && navigator.userAgent.search("Chrome") < 0) 
{
   alert("Browser is Safari");          
}

This code is used to detect only safari browser

if (navigator.userAgent.search("Safari") >= 0 && navigator.userAgent.search("Chrome") < 0) 
{
   alert("Browser is Safari");          
}
悲歌长辞 2024-12-19 17:09:20

因为 chrome 和 safari 的 userAgent 几乎相同,所以可以更容易地查看浏览器的供应商

Safari

navigator.vendor ==  "Apple Computer, Inc."

Chrome

navigator.vendor ==  "Google Inc."

FireFox (为什么是这样空?)

navigator.vendor ==  ""

IE(为什么它是未定义的?)

navigator.vendor ==  undefined

Because userAgent for chrome and safari are nearly the same it can be easier to look at the vendor of the browser

Safari

navigator.vendor ==  "Apple Computer, Inc."

Chrome

navigator.vendor ==  "Google Inc."

FireFox (why is it empty?)

navigator.vendor ==  ""

IE (why is it undefined?)

navigator.vendor ==  undefined
一百个冬季 2024-12-19 17:09:20

阅读许多答案和帖子并确定最准确的解决方案。在 Safari、Chrome、Firefox 和 Firefox 中进行了测试Opera(桌面版和 iOS 版)。首先我们需要检测 Apple 供应商,然后排除 Chrome、Firefox 和 Firefox。 Opera(适用于 iOS)。

let isSafari = navigator.vendor.match(/apple/i) &&
             !navigator.userAgent.match(/crios/i) &&
             !navigator.userAgent.match(/fxios/i) &&
             !navigator.userAgent.match(/Opera|OPT\//);

if (isSafari) {
  // Safari browser is used
} else {
  // Other browser is used
}

Read many answers and posts and determined the most accurate solution. Tested in Safari, Chrome, Firefox & Opera (desktop and iOS versions). First we need to detect Apple vendor and then exclude Chrome, Firefox & Opera (for iOS).

let isSafari = navigator.vendor.match(/apple/i) &&
             !navigator.userAgent.match(/crios/i) &&
             !navigator.userAgent.match(/fxios/i) &&
             !navigator.userAgent.match(/Opera|OPT\//);

if (isSafari) {
  // Safari browser is used
} else {
  // Other browser is used
}
打小就很酷 2024-12-19 17:09:20

检测手势更改支持,如下所示:

const isSafari = !!window.GestureEvent
document.write(isSafari ? "You are using Safari." : "You are not using Safari.")

漂亮又简单;适用于 iOS 和 Android!如果您需要 ES5 支持,请将 const 替换为 var

请注意,如果人们使用 WKWebView 进行针对 Apple 设备的应用程序开发,它可能会声称它是 Safari,这在技术上是正确的,因为它在后台使用 Safari 的网络功能。可能需要其他解决方案,例如注入额外的代码。

Detect gesture change support, like this:

const isSafari = !!window.GestureEvent
document.write(isSafari ? "You are using Safari." : "You are not using Safari.")

Nice and simple; works for iOS and Android! If you need ES5 support, replace const with var.

Note that if people are using WKWebView for app development tailored to an Apple device, it may claim it is Safari, which is technically true, given that it uses Safari's web features in the background. Other solutions may be necessary, such as injecting additional code.

吖咩 2024-12-19 17:09:20

我不知道为什么OP想要检测Safari,但在极少数情况下,您现在需要浏览器嗅探,检测渲染引擎可能比检测浏览器名称更重要。例如,在 iOS 上,所有浏览器都使用 Safari/Webkit 引擎,因此如果底层渲染器实际上是 Safari/Webkit,那么使用“chrome”或“firefox”作为浏览器名称是没有意义的。我还没有在旧浏览器上测试过这段代码,但它适用于 Android、iOS、OS X、Windows 和 Linux 上的所有最新版本。

<script>
    let browserName = "";

    if(navigator.vendor.match(/google/i)) {
        browserName = 'chrome/blink';
    }
    else if(navigator.vendor.match(/apple/i)) {
        browserName = 'safari/webkit';
    }
    else if(navigator.userAgent.match(/firefox\//i)) {
        browserName = 'firefox/gecko';
    }
    else if(navigator.userAgent.match(/edge\//i)) {
        browserName = 'edge/edgehtml';
    }
    else if(navigator.userAgent.match(/trident\//i)) {
        browserName = 'ie/trident';
    }
    else
    {
        browserName = navigator.userAgent + "\n" + navigator.vendor;
    }
    alert(browserName);
</script>

澄清一下:

  • iOS 下的所有浏览器都将报告为“safari/webkit”
  • Android 下除 Firefox 之外的所有浏览器都将报告为“chrome/blink”
  • Chrome、Opera、Blisk、Vivaldi 等都将报告为“chrome/blink”在 Windows、OS X 或 Linux 下

I don't know why the OP wanted to detect Safari, but in the rare case you need browser sniffing nowadays it's problably more important to detect the render engine than the name of the browser. For example on iOS all browsers use the Safari/Webkit engine, so it's pointless to get "chrome" or "firefox" as browser name if the underlying renderer is in fact Safari/Webkit. I haven't tested this code with old browsers but it works with everything fairly recent on Android, iOS, OS X, Windows and Linux.

<script>
    let browserName = "";

    if(navigator.vendor.match(/google/i)) {
        browserName = 'chrome/blink';
    }
    else if(navigator.vendor.match(/apple/i)) {
        browserName = 'safari/webkit';
    }
    else if(navigator.userAgent.match(/firefox\//i)) {
        browserName = 'firefox/gecko';
    }
    else if(navigator.userAgent.match(/edge\//i)) {
        browserName = 'edge/edgehtml';
    }
    else if(navigator.userAgent.match(/trident\//i)) {
        browserName = 'ie/trident';
    }
    else
    {
        browserName = navigator.userAgent + "\n" + navigator.vendor;
    }
    alert(browserName);
</script>

To clarify:

  • All browsers under iOS will be reported as "safari/webkit"
  • All browsers under Android but Firefox will be reported as "chrome/blink"
  • Chrome, Opera, Blisk, Vivaldi etc. will all be reported as "chrome/blink" under Windows, OS X or Linux
铜锣湾横着走 2024-12-19 17:09:20

就我而言,我需要在 iOS 和 macOS 上定位 Safari。这对我有用:

if (/apple/i.test(navigator.vendor)) {
  // It's Safari
}

In my case I needed to target Safari on both iOS and macOS. This worked for me:

if (/apple/i.test(navigator.vendor)) {
  // It's Safari
}
半世晨晓 2024-12-19 17:09:20

只有 Safari 没有 Chrome:

在尝试其他代码后,我没有找到任何适用于新旧版本 Safari 的代码。

最后,我编写了这段对我来说非常有效的代码:

var ua = navigator.userAgent.toLowerCase(); 
var isSafari = false;
try {
  isSafari = /constructor/i.test(window.HTMLElement) || (function (p) { return p.toString() === "[object SafariRemoteNotification]"; })(!window['safari'] || safari.pushNotification);
}
catch(err) {}
isSafari = (isSafari || ((ua.indexOf('safari') != -1)&& (!(ua.indexOf('chrome')!= -1) && (ua.indexOf('version/')!= -1))));

//test
if (isSafari)
{
  //Code for Safari Browser (Desktop and Mobile)
  document.getElementById('idbody').innerHTML = "This is Safari!";
}
else
{
  document.getElementById('idbody').innerHTML = "This is not Safari!";
}
<body id="idbody"></body>

Only Safari whitout Chrome:

After trying other's code I didn't find any that works with new and old versions of Safari.

Finally, I did this code that's working very well for me:

var ua = navigator.userAgent.toLowerCase(); 
var isSafari = false;
try {
  isSafari = /constructor/i.test(window.HTMLElement) || (function (p) { return p.toString() === "[object SafariRemoteNotification]"; })(!window['safari'] || safari.pushNotification);
}
catch(err) {}
isSafari = (isSafari || ((ua.indexOf('safari') != -1)&& (!(ua.indexOf('chrome')!= -1) && (ua.indexOf('version/')!= -1))));

//test
if (isSafari)
{
  //Code for Safari Browser (Desktop and Mobile)
  document.getElementById('idbody').innerHTML = "This is Safari!";
}
else
{
  document.getElementById('idbody').innerHTML = "This is not Safari!";
}
<body id="idbody"></body>

绝不放开 2024-12-19 17:09:20

我发现只有一个词可以区分 Safari:“版本”。所以这个正则表达式将完美工作:

/.*Version.*Safari.*/.test(navigator.userAgent)

I observed that only one word distinguishes Safari - "Version". So this regex will work perfect:

/.*Version.*Safari.*/.test(navigator.userAgent)
空名 2024-12-19 17:09:20

我用这个

function getBrowserName() {
    var name = "Unknown";
    if(navigator.userAgent.indexOf("MSIE")!=-1){
        name = "MSIE";
    }
    else if(navigator.userAgent.indexOf("Firefox")!=-1){
        name = "Firefox";
    }
    else if(navigator.userAgent.indexOf("Opera")!=-1){
        name = "Opera";
    }
    else if(navigator.userAgent.indexOf("Chrome") != -1){
        name = "Chrome";
    }
    else if(navigator.userAgent.indexOf("Safari")!=-1){
        name = "Safari";
    }
    return name;   
}

if( getBrowserName() == "Safari" ){
    alert("You are using Safari");
}else{
    alert("You are surfing on " + getBrowserName(name));
}

I use this

function getBrowserName() {
    var name = "Unknown";
    if(navigator.userAgent.indexOf("MSIE")!=-1){
        name = "MSIE";
    }
    else if(navigator.userAgent.indexOf("Firefox")!=-1){
        name = "Firefox";
    }
    else if(navigator.userAgent.indexOf("Opera")!=-1){
        name = "Opera";
    }
    else if(navigator.userAgent.indexOf("Chrome") != -1){
        name = "Chrome";
    }
    else if(navigator.userAgent.indexOf("Safari")!=-1){
        name = "Safari";
    }
    return name;   
}

if( getBrowserName() == "Safari" ){
    alert("You are using Safari");
}else{
    alert("You are surfing on " + getBrowserName(name));
}
月下伊人醉 2024-12-19 17:09:20

最简单的答案:

function isSafari() {
 if (navigator.vendor.match(/[Aa]+pple/g).length > 0 ) 
   return true; 
 return false;
}

Simplest answer:

function isSafari() {
 if (navigator.vendor.match(/[Aa]+pple/g).length > 0 ) 
   return true; 
 return false;
}
豆芽 2024-12-19 17:09:20

修改了答案的正则表达式上述

var isSafari = /^((?!chrome|android|crios|fxios).)*safari/i.test(navigator.userAgent);
  • crios - Chrome
  • fxios - Firefox

Modified regex for answer above

var isSafari = /^((?!chrome|android|crios|fxios).)*safari/i.test(navigator.userAgent);
  • crios - Chrome
  • fxios - Firefox
安人多梦 2024-12-19 17:09:20

我知道这个问题已经很老了,但我还是想发布答案,因为它可能会对某人有所帮助。上述解决方案在某些边缘情况下会失败,因此我们必须以分别处理 iOS、桌面和其他平台的方式来实现它。

function isSafari() {
    var ua = window.navigator.userAgent;
    var iOS = !!ua.match(/iP(ad|od|hone)/i);
    var hasSafariInUa = !!ua.match(/Safari/i);
    var noOtherBrowsersInUa = !ua.match(/Chrome|CriOS|OPiOS|mercury|FxiOS|Firefox/i)
    var result = false;
    if(iOS) { //detecting Safari in IOS mobile browsers
        var webkit = !!ua.match(/WebKit/i);
        result = webkit && hasSafariInUa && noOtherBrowsersInUa
    } else if(window.safari !== undefined){ //detecting Safari in Desktop Browsers
        result = true;
    } else { // detecting Safari in other platforms
        result = hasSafariInUa && noOtherBrowsersInUa
    }
    return result;
}

I know this question is old, but I thought of posting the answer anyway as it may help someone. The above solutions were failing in some edge cases, so we had to implement it in a way that handles iOS, Desktop, and other platforms separately.

function isSafari() {
    var ua = window.navigator.userAgent;
    var iOS = !!ua.match(/iP(ad|od|hone)/i);
    var hasSafariInUa = !!ua.match(/Safari/i);
    var noOtherBrowsersInUa = !ua.match(/Chrome|CriOS|OPiOS|mercury|FxiOS|Firefox/i)
    var result = false;
    if(iOS) { //detecting Safari in IOS mobile browsers
        var webkit = !!ua.match(/WebKit/i);
        result = webkit && hasSafariInUa && noOtherBrowsersInUa
    } else if(window.safari !== undefined){ //detecting Safari in Desktop Browsers
        result = true;
    } else { // detecting Safari in other platforms
        result = hasSafariInUa && noOtherBrowsersInUa
    }
    return result;
}
总攻大人 2024-12-19 17:09:20

2023年版

if(navigator.userAgent.includes('Safari') && !navigator.userAgent.includes('Chrome')){
    // it's safari
    console.log('safari detected');
}

2023 edition

if(navigator.userAgent.includes('Safari') && !navigator.userAgent.includes('Chrome')){
    // it's safari
    console.log('safari detected');
}
伴我老 2024-12-19 17:09:20

2024 版本

  var ua = window.navigator.userAgent;
  var iOS = ua.match(/Macintosh/i) || ua.match(/iPad/i) || ua.match(/iPhone/i);
  var webkit = ua.match(/WebKit/i);
  var iOSSafari = iOS && webkit && !ua.match(/CriOS/i) && !ua.match(/EdgiOS/i) && !ua.match(/Chrome/i) && !ua.match(/Edg/i);

    if (iOSSafari) {
        //do stuff here
    }

2024 Version

  var ua = window.navigator.userAgent;
  var iOS = ua.match(/Macintosh/i) || ua.match(/iPad/i) || ua.match(/iPhone/i);
  var webkit = ua.match(/WebKit/i);
  var iOSSafari = iOS && webkit && !ua.match(/CriOS/i) && !ua.match(/EdgiOS/i) && !ua.match(/Chrome/i) && !ua.match(/Edg/i);

    if (iOSSafari) {
        //do stuff here
    }
眼眸里的那抹悲凉 2024-12-19 17:09:20

根据记录,我发现的最安全的方法是实现此答案中的浏览器检测代码的 Safari 部分:

const isSafari = window['safari'] && safari.pushNotification &&
    safari.pushNotification.toString() === '[object SafariRemoteNotification]';

当然,如果可能的话,处理特定于浏览器的问题的最佳方法始终是进行功能检测。不过,使用像上面这样的一段代码仍然比代理字符串检测更好。

For the records, the safest way I've found is to implement the Safari part of the browser-detection code from this answer:

const isSafari = window['safari'] && safari.pushNotification &&
    safari.pushNotification.toString() === '[object SafariRemoteNotification]';

Of course, the best way of dealing with browser-specific issues is always to do feature-detection, if at all possible. Using a piece of code like the above one is, though, still better than agent string detection.

々眼睛长脚气 2024-12-19 17:09:20

这个独特的“问题”100% 表明浏览器是 Safari(不管你信不信)。

if (Object.getOwnPropertyDescriptor(Document.prototype, 'cookie').descriptor === false) {
   console.log('Hello Safari!');
}

这意味着 Cookie 对象描述符在 Safari 上设置为 false,而在其他所有浏览器上设置为 true,这实际上是让我对另一个项目感到头疼。快乐编码!

This unique "issue" is 100% sign that browser is Safari (believe it or not).

if (Object.getOwnPropertyDescriptor(Document.prototype, 'cookie').descriptor === false) {
   console.log('Hello Safari!');
}

This means that cookie object descriptor is set to false on Safari while on the all other is true, which is actually giving me a headache on the other project. Happy coding!

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文