IT TIP

Chrome 및 Safari 브라우저 (웹킷)를 감지하는 방법

itqueen 2020. 12. 13. 11:32
반응형

Chrome 및 Safari 브라우저 (웹킷)를 감지하는 방법


jquery 또는 javascript를 사용하여 크롬 및 사파리 브라우저를 감지하려고합니다. jQuery.browser를 사용해서는 안된다고 생각했습니다. 여기에 제안이 있습니까? 감사합니다!


을 사용하고 싶지 않다면 사례 1을$.browser 살펴보십시오 . 그렇지 않으면 사례 23 이 사용을 권장하지 않기 때문에 정보 를 얻는 데 도움이 될 수 있습니다 (사용자 에이전트가 이것을 사용하여 스푸핑 될 수 있음). 에이전트 정보가 아닌 기능 지원을 감지 하는 대안을 사용할 수 있습니다 .$.browserjQuery.support

그러나...

브라우저 유형 (Chrome 또는 Safari)을 사용 $.browser하고 싶지만을 사용하지 않으려 경우 case 1 이 찾고있는 것입니다.


이것은 귀하의 요구 사항에 적합합니다.

사례 1 : (jQuery 및 $ .browser 없음, 자바 스크립트 만)

라이브 데모 : http://jsfiddle.net/oscarj24/DJ349/

var isChrome = /Chrome/.test(navigator.userAgent) && /Google Inc/.test(navigator.vendor);
var isSafari = /Safari/.test(navigator.userAgent) && /Apple Computer/.test(navigator.vendor);

if (isChrome) alert("You are using Chrome!");
if (isSafari) alert("You are using Safari!");

이런 경우는 예전에 사용하고 잘 작동했지만 권장하지 않습니다.

사례 2 : (jQuery와 $ .browser를 사용하면 까다 롭습니다)

라이브 데모 : http://jsfiddle.net/oscarj24/gNENk/

$(document).ready(function(){

    /* Get browser */
    $.browser.chrome = /chrome/.test(navigator.userAgent.toLowerCase());

    /* Detect Chrome */
    if($.browser.chrome){
        /* Do something for Chrome at this point */
        /* Finally, if it is Chrome then jQuery thinks it's 
           Safari so we have to tell it isn't */
        $.browser.safari = false;
    }

    /* Detect Safari */
    if($.browser.safari){
        /* Do something for Safari */
    }

});

사례 3 : (jQuery 및 $ .browser 사용, "우아한"솔루션)

라이브 데모 : http://jsfiddle.net/oscarj24/uJuEU/

$.browser.chrome = $.browser.webkit && !!window.chrome;
$.browser.safari = $.browser.webkit && !window.chrome;

if ($.browser.chrome) alert("You are using Chrome!");
if ($.browser.safari) alert("You are using Safari!");

여기에있는 대부분의 답변은 구식이며 더 이상 존재하지 않으며 jQuery.browser왜 누군가가 jQuery를 사용하거나 User Agent저를 넘어서는 냄새를 맡을 것입니다.

브라우저를 감지하는 대신 기능 (지원 여부에 관계없이)을 감지해야합니다 .
다음은 falseMozilla Firefox, Microsoft Edge에 있습니다. 그는 true구글 크롬에.

"webkitLineBreak" in document.documentElement.style

이것은 미래 보장이 아닙니다. 브라우저 -webkit-line-break는 나중에 언제든지 속성을 구현할 수 있으므로 잘못된 감지가 발생할 수 있습니다. 그런 다음 Chrome에서 문서 개체를보고 webkit접두사가있는 항목을 선택 하고 다른 브라우저에서 누락되었는지 확인할 수 있습니다.


브라우저를 감지하는 대신 기능 (지원 여부에 관계없이)을 감지해야합니다. 이것이 Modernizr가하는입니다.

물론 기능을 감지하지 않고 문제를 해결해야하기 때문에 여전히 브라우저를 확인해야하는 경우가 있습니다. WebKitjQuery를 사용하지 않는 특정 검사 $.browser:

var isWebKit = !!window.webkitURL;

일부 의견에 따르면 위의 접근 방식은 이전 Safari 버전에서는 작동하지 않습니다. 의견 및 다른 답변에서 제안 된 다른 접근 방식으로 업데이트 :

var isWebKit = 'WebkitAppearance' in document.documentElement.style;

2019 년에도 여전히 단점과 불일치가 있습니다.

예를 들어, 확장 된 svg 및 포인터 이벤트, 브라우저 간.

이 주제에 대한 답변은 더 이상 작동하지 않습니다. (아마도 jquery가 있는 사람들 )

다음은 네이티브 CSS 지원 API 를 통해 CSS 규칙이 지원되는 경우 자바 스크립트로 테스트 하는 대안 입니다. 적응하기 위해 진화 할 수 있습니다!

최상의 감지를 위해 세미콜론으로 구분 된 많은 CSS 규칙을 전달할 수 있습니다.

if (CSS.supports("( -webkit-box-reflect:unset )")){
  console.log("WEBKIT BROWSER")
  // More math...
 } else {
  console.log("ENJOY")
 }

if (CSS.supports("( -moz-user-select:unset )")){
  console.log("FIREFOX!!!")
 }

루프에서 사용하지 않도록주의하십시오. 성능을 위해로드시 상수를 채우는 것이 좋습니다.

const ff = CSS.supports("( -moz-user-select:unset )")
if (ff){ //... } 

CSS 만 사용 하면 위의 내용은 다음과 같습니다.

@supports (-webkit-box-reflect:unset) {
  div {
    background: red
  }
}

@supports (-moz-user-select:unset) {
  div {
    background: green
  }
}
<div>
  Hello world!!
</div>

가능한 -webkit- 전용 CSS 규칙 목록입니다.

가능한 -moz- 전용 규칙 목록입니다.

CSS 지원을 사용할 수 있습니까?


/WebKit/.test(navigator.userAgent) -그게 다야.


jquery 또는 javascript를 사용하여 크롬 및 사파리 브라우저를 감지하려고합니다.

사용하다 jQuery.browser

jQuery.browser를 사용해서는 안된다고 생각했습니다.

브라우저를 감지하는 것은 나쁜 생각이기 때문입니다. 정말로 그렇게하려는 경우 브라우저 (jQuery가 관련되었을 때)를 감지하는 가장 좋은 방법입니다.


이 축소 된 jQuery 스 니펫을 사용하여 사용자가 모바일 장치를 사용하여보고 있는지 감지 할 수 있습니다. 특정 장치를 테스트해야하는 경우 iPad, iPhone, iPod, iDevice, Andriod, Blackberry, WebOs 및 Windows Phone과 같은 다양한 모바일 핸드 헬드 장치를 감지하는 데 사용할 수있는 JavaScript 스 니펫 모음을 아래에 포함했습니다.

/**
 * jQuery.browser.mobile (http://detectmobilebrowser.com/)
 * jQuery.browser.mobile will be true if the browser is a mobile device
 **/

    (function(a){jQuery.browser.mobile=/android.+mobile|avantgo|bada/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)/|plucker|pocket|psp|symbian|treo|up.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino/i.test(a)||/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw-(n|u)|c55/|capi|ccwa|cdm-|cell|chtm|cldc|cmd-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc-s|devi|dica|dmob|do(c|p)o|ds(12|-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(-|_)|g1 u|g560|gene|gf-5|g-mo|go(.w|od)|gr(ad|un)|haie|hcit|hd-(m|p|t)|hei-|hi(pt|ta)|hp( i|ip)|hs-c|ht(c(-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i-(20|go|ma)|i230|iac( |-|/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |/)|klon|kpt |kwc-|kyo(c|k)|le(no|xi)|lg( g|/(k|l|u)|50|54|e-|e/|-[a-w])|libw|lynx|m1-w|m3ga|m50/|ma(te|ui|xo)|mc(01|21|ca)|m-cr|me(di|rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|-([1-8]|c))|phil|pire|pl(ay|uc)|pn-2|po(ck|rt|se)|prox|psio|pt-g|qa-a|qc(07|12|21|32|60|-[2-7]|i-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55/|sa(ge|ma|mm|ms|ny|va)|sc(01|h-|oo|p-)|sdk/|se(c(-|0|1)|47|mc|nd|ri)|sgh-|shar|sie(-|m)|sk-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h-|v-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl-|tdg-|tel(i|m)|tim-|t-mo|to(pl|sh)|ts(70|m-|m3|m5)|tx-9|up(.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|xda(-|2|g)|yas-|your|zeto|zte-/i.test(a.substr(0,4))})(navigator.userAgent||navigator.vendor||window.opera);

사용 예 :

if(jQuery.browser.mobile)
{
console.log(‘You are using a mobile device!’);
}
else
{
console.log(‘You are not using a mobile device!’);
}

iPad 감지

var isiPad = /ipad/i.test(navigator.userAgent.toLowerCase());
if (isiPad)
{
}

iPhone 감지

var isiPhone = /iphone/i.test(navigator.userAgent.toLowerCase());
if (isiPhone)
{
}

iPod 감지

var isiPod = /ipod/i.test(navigator.userAgent.toLowerCase());
if (isiPod)
{
}

iDevice 감지

var isiDevice = /ipad|iphone|ipod/i.test(navigator.userAgent.toLowerCase());

if (isiDevice)
{
}

Andriod 감지

var isAndroid = /android/i.test(navigator.userAgent.toLowerCase());

if (isAndroid)
{
}

Blackberry 감지

var isBlackBerry = /blackberry/i.test(navigator.userAgent.toLowerCase());

if (isBlackBerry)
{
}

WebO 감지

var isWebOS = /webos/i.test(navigator.userAgent.toLowerCase());

if (isWebOS)
{
}

Windows Phone 감지

var isWindowsPhone = /windows phone/i.test(navigator.userAgent.toLowerCase());

if (isWindowsPhone)
{
}

여기에 많은 답변이 있습니다. 첫 번째 고려 사항입니다.

JavaScript가 없으면 보안 목적으로 사용자가 자신의 브라우저에서 Javascript를 비활성화하고 사용자가 사이트를 신뢰하는 경우 사용자가 화이트리스트에 올릴 가능성을 포함하여 Javascript가 꺼져 있기 때문에 DOM을 사용할 수 없습니다.

프로그래밍 방식으로 백엔드 서버 측 또는 프런트 엔드 클라이언트 측 고려 사항이 남아 있습니다.

With the backend, you can use common denominator HTTP "User-Agent" request header and/or any possible proprietary HTTP request header issued by the browser to output browser specific HTML stuff.

With the client site, you may want to enforce Javascript to allow you to use DOM. If so, then you probably will want to first use the following in your HTML page:

<noscript>This site requires Javascript. Please turn on Javascript.</noscript>

While we are heading to a day with every web coder will be dependent on Javascript in some way (or not), today, to presume every user has javascript enabled would be design and product development QA mistake.

I've seen far too may sites who end up with a blank page or the site breaks down because it presumed every user has javascript enabled. No. For security purposes, they may have Javascript initially off and some browsers, like Chrome, will allow the user to white list the web site on a domain by domain basis. Edge is the only browser I am aware of where Microsoft made the decision to completely disable the user's ability to turn off Javascript. Edge doesn't offer a white listing concept hence it is one reason I don't personally use Edge.

Using the tag is a simple way to inform the user your site won't work without Javascript. Once the user turns it on and refreshes/reload the page, DOM is now available to use the techniques cited by the thread replies to detect chrome vs safari.

Ironically, I got here because I was updating by platform and google the same basic question; chrome vs sarafi. I didn't know Chrome creates a DOM object named "chrome" which is really all you need to detect "chrome" vs everything else.

var isChrome = typeof(chrome) === "object";

If true, you got Chrome, if false, you got some other browser.

Check to see if Safari create its own DOM object as well, if so, get the object name and do the same thing, for example:

var isSafari = (typeof(safari) === "object");

Hope these tips help.


jQuery provides that:

if ($.browser.webkit){
    ...
}

Further reading at http://api.jquery.com/jQuery.browser/

Update

As noted in other answers/comments, it's always better to check for feature support than agent info. jQuery also provides an object for that: jQuery.support. Check the documentation to see the detailed list features to check for.

참고URL : https://stackoverflow.com/questions/12625876/how-to-detect-chrome-and-safari-browser-webkit

반응형