브라우저 감지 jQuery 1.9를위한 가장 가벼운 교체?
어제 여러 고객이 일부 코드가 작동을 멈춘다 고 불평했습니다. 분명히 그것은 jQuery.browser
jQuery 1.9가 노출 때 어제 작동을 멈춘 현재 사용하지 않는 사용하는 것 입니다.
나는 (빠르게) 1.9 변경 문서를 선호 하고 그들이 하나의 기능을 위해 꽤 무거운 라이브러리를 대체하기 원하는 것 입니다.
해당 기능을 복원하기 위해 권장되는 가장 가벼운 또는 코드 스 니펫이 있습니까?
필요한 것은 매우 기본입니다. IE 대 FF 대 다른 모든 사람에 대한 가장 기본적인 탐지 만 필요합니다.
제안?
Alexx Roche가 답변 한 다음 코드를 사용했지만 MSIE를 감지하고 싶었습니다.
<script type="text/javascript">
$(document).ready(function() {
if (navigator.userAgent.match(/msie/i) ){
alert('I am an old fashioned Internet Explorer');
}
});
</script>
도움이 되길 바랍니다!
jQuery Migrate는 코드를 업데이트하는 동안 이전 버전과의 규격을 허용하기 위해 만들어졌습니다 .
https://github.com/jquery/jquery-migrate
보너스로 사용하지 않는 기능을 사용할 때 기록합니다. 문제를 해결하는 동안 시도해 보겠습니다. 또한 사이트에 특정 버전의 jQuery를 설정해야합니다. 업그레이드하는 것이 좋지만 설치하기 전에 업그레이드를 테스트해야합니다. CDN을 사용하는 경우에도 파일 이름에 특정 버전을 수 있습니다.
이제 당신이 요구하는 것이 필요하지 않습니다 . 확인 개체를 .navigator
appCodeName: "Mozilla"
appName: "Netscape"
appVersion: "5.0 (Macintosh; Intel Mac OS X 10_6_8) AppleWebKit/537.17 (KHTML, like Gecko) Chrome/24.0.1312.52 Safari/537.17"
cookieEnabled: true
doNotTrack: null
geolocation: Geolocation
language: "en-US"
mimeTypes: MimeTypeArray
onLine: true
platform: "MacIntel"
plugins: PluginArray
product: "Gecko"
productSub: "20030107"
userAgent: "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_6_8) AppleWebKit/537.17 (KHTML, like Gecko) Chrome/24.0.1312.52 Safari/537.17"
vendor: "Google Inc."
vendorSub: ""
var browser = {
chrome: false,
mozilla: false,
opera: false,
msie: false,
safari: false
};
var sUsrAg = navigator.userAgent;
if(sUsrAg.indexOf("Chrome") > -1) {
browser.chrome = true;
} else if (sUsrAg.indexOf("Safari") > -1) {
browser.safari = true;
} else if (sUsrAg.indexOf("Opera") > -1) {
browser.opera = true;
} else if (sUsrAg.indexOf("Firefox") > -1) {
browser.mozilla = true;
} else if (sUsrAg.indexOf("MSIE") > -1) {
browser.msie = true;
}
console.log(browser.msie);
이 코드를 사이트에 등록하십시오 (예 : js 파일 또는 jQuery 코드 ...).
var matched, browser;
// Use of jQuery.browser is frowned upon.
// More details: http://api.jquery.com/jQuery.browser
// jQuery.uaMatch maintained for back-compat
jQuery.uaMatch = function( ua ) {
ua = ua.toLowerCase();
var match = /(chrome)[ \/]([\w.]+)/.exec( ua ) ||
/(webkit)[ \/]([\w.]+)/.exec( ua ) ||
/(opera)(?:.*version|)[ \/]([\w.]+)/.exec( ua ) ||
/(msie) ([\w.]+)/.exec( ua ) ||
ua.indexOf("compatible") < 0 && /(mozilla)(?:.*? rv:([\w.]+)|)/.exec( ua ) ||
[];
return {
browser: match[ 1 ] || "",
version: match[ 2 ] || "0"
};
};
matched = jQuery.uaMatch( navigator.userAgent );
browser = {};
if ( matched.browser ) {
browser[ matched.browser ] = true;
browser.version = matched.version;
}
// Chrome is Webkit, but Webkit is also Safari.
if ( browser.chrome ) {
browser.webkit = true;
} else if ( browser.webkit ) {
browser.safari = true;
}
jQuery.browser = browser;
동일한 문제가 발생했을 때 다음 코드를 사용했습니다.
<script type="text/javascript">
$(document).ready(function() {
//if (!$.browser.webkit && ! $.browser.mozilla) { //depricated
if (!navigator.userAgent.match(/mozilla/i) &&
! navigator.userAgent.match(/webkit/i) ){
alert('Let me tell you about Mozilla');
}
});
</script>
감가 상각 방법에서 때까지 업데이트 할 수 없습니다.
어쨌든 버전 번호를 지정하지 않고 CDN에서 jquery를 지정하지 않습니다. 이것은 CDN (캐싱 없음)을 사용하는 목적에 위배됩니다.
다음은 $ .browser를 지원하는 최신 버전의 jQuery에 대한 링크입니다.
http://code.jquery.com/jquery-1.8.3.min.js
jquery.js src를 해당 링크로 바꾸면 앞으로 나아갈 준비가 될 때까지 코드가 계속 실행되고 감가 상각 된 기능 사용을 중지 할 수 있습니다.
참고 : Fancybox2는 여전히 $ .browser를 사용하는데, 이것이 업데이트 이후까지 본 것 중 가장 일반적인 것입니다.
업데이트 : Slickgrid는 여전히 사용 중이며 2013 $.browser
년 2 월 11 일 현재 업데이트가 없습니다.
jQuery.browser를 사용하여 jquery.browser를 사용하여 추상화했습니다 . MIT 라이선스에 따라 출시되었습니다.
IE11, Opera Webkit 및 Android 감지에 대한 지원도 추가되었습니다.
Conditionizr 구경보기
도움이 되셨기를 바랍니다. :)
특정 IE 버전에 추가 된 표준 전역 개체의 존재 여부를 추가로 확인하여 정확한 버전의 IE를 검색 할 수 있습니다.
10 or older document.all
9 or older document.all && !window.atob
8 or older document.all && !document.addEventListener
7 or older document.all && !document.querySelector
6 or older document.all && !window.XMLHttpRequest
5.x document.all && !document.compatMode
if (document.all && !document.querySelector) {
alert('IE7 or lower');
}
이 테스트는 사용되는 userAgent를 사용하지 않습니다.
if(!$.browser){
$.browser={chrome:false,mozilla:false,opera:false,msie:false,safari:false};
var ua=navigator.userAgent;
$.each($.browser,function(c,a){
$.browser[c]=((new RegExp(c,'i').test(ua)))?true:false;
if($.browser.mozilla && c =='mozilla'){$.browser.mozilla=((new RegExp('firefox','i').test(ua)))?true:false;};
if($.browser.chrome && c =='safari'){$.browser.safari=false;};
});
};
제 3 자 jQuery 플러그인이 jQuery.browser.msie를 사용할 수 있습니다. 여기에 한 줄짜리가 있습니다. jQuery 다음에 꼭하십시오.
jQuery.browser = jQuery.browser || {msie: navigator.userAgent.match(/msie/i) ? true : false};
이것은 가장 멍청한 해결책이지만 내가 필요한 전부이며 작동하는 여기에 있습니다!
이 토론에 추가합니다. '감지'대신 사용자 에이전트를 사용하기 쉬운 개체로 구문 분석하는 jquery $ .browser 방금 사용해보세요. 추가로 쉽게 적용하여 특정 브라우저 및 플랫폼을 추가로 분석하고 구문 분석 할 수 있습니다.
나는 useragents에 매우 많은 수있는 결과를 가지고 있었다 : UserAgentString.com . ie11 (하단 근처)에 대한 버전 감지도 포함했습니다.
//The following code is by no means perfect, nor is it meant to be a standalone 'detection' plugin.
//It demonstrates parsing the useragent string into an easy to manage object.
//Even if it does make detection rediculously easy.. :)
//Because this regex makes no assumptions in advance.
//IMO, It's compatibilty and maintainability is much higher than those based on static identifiers.
/*
uaMatch replacement that parses a useragent string into an object
useragent segments can be Name Value OR Name/Value OR Name
Segment: Name Value
Name: parsed to the last whitespace character
Value: value after the last whitespace character
Matches: (.NET CLR) (#.##), Android 2.3.4, etc
Note: this regex can have leading/trailing whitespace (trimmed for object properties)
Segment: Name/Value
Matches: all values matching Name/Value
Example: Firefox/24.0, Safari/533.1, Version/12.1, etc
Segment: Name
Matches: identifiers that hold no values (value of 'true' is implied)
Example: Macintosh, Linux, Windows, KHTML, U, etc
WARNING: not necessarily compatible with jQuery's $.browser implementation.
- not recommended as a replacement for plugins that require it to function.
*/
(function ($) {
var ua = navigator.userAgent.toLowerCase();
var regex = /compatible; ([\w.+]+)[ \/]([\w.+]*)|([\w .+]+)[: \/]([\w.+]+)|([\w.+]+)/g;
var match = regex.exec(ua);
var browser = { };
while (match != null) {
var prop = {};
if (match[1]) {
prop.type = match[1];
prop.version = match[2];
}
else if (match[3]) {
prop.type = match[3];
prop.version = match[4];
}
else {
prop.type = match[5];
}
// some expressions have leading whitespace (i couldn't avoid this without a more complex expression)
// trim them and get rid of '.' (' .NET CLR' = 'net_clr')
prop.type = $.trim(prop.type).replace(".","").replace(" ","_");
var value = prop.version ? prop.version : true;
if (browser[prop.type]) {
if (!$.isArray(browser[prop.type]))
browser[prop.type] = new Array(browser[prop.type]);
browser[prop.type].push(value);
}
else browser[prop.type] = value;
match = regex.exec(ua);
}
for (var i in browser)
if (i.indexOf("mac") > -1)
browser.mac = true;
if (browser.windows_nt && !browser.windows)
browser.windows = true;
//put known browsers into the 'version' property for 'some' jquery compatibility
//for sake of argument chromium 'is' chrome
if (browser.chromium && !browser.chrome)
browser.chrome = browser.chromium;
//chrome / safari / webkit
if (browser.chrome) {
browser.version = browser.chrome;
}
else if (browser.safari) {
browser.version = browser.safari;
}
else {
if (browser.applewebkit)
browser.webkit = browser.applewebkit;
if (browser.webkit)
browser.version = browser.webkit;
}
//firefox / gecko
if (browser.firefox) {
if (browser.rv)
browser.version = browser.rv;
else browser.version = browser.firefox;
}
else if (browser.gecko) {
if (browser.rv)
browser.version = browser.rv;
else browser.version = browser.gecko;
}
//opera
if (browser.opera && !browser.version)
browser.version = browser.opera;
//msie
if (browser.trident && browser.rv) //ie11
browser.msie = browser.rv;
if (browser.msie)
browser.version = browser.msie;
$.browser = browser;//Rename to reduce confliction?
//WAS USED FOR TESTING & DISCOVERY (very useful)
//TODO: remove line below
alert(JSON.stringify($.browser));
}) (jQuery);
Internet Explorer 10에서 JSON.stringify는 다음과 같이 출력됩니다.
{"mozilla":"5.0","msie":"10.0","windows_nt":"6.2","trident":"6.0","net4.0e":true,"net4.0c":true,"net_clr":["3.5.30729","2.0.50727","3.0.30729"],"windows":true,"version":"10.0"}
짧지 만 강력합니다.
// chrome, safari, webkit, mozilla, msie, opera
var chrome = /chrome/i.test(navigator.userAgent);
'ProgramingTip' 카테고리의 다른 글
명령의 배열에 할당 할당입니까? (0) | 2020.11.27 |
---|---|
C의 수학 상수 PI 값 (0) | 2020.11.27 |
TabWidget 현재 탭 하단 선 색상 (0) | 2020.11.27 |
SSL에 대한 Apache 2.4 구성이 작동하지 않음 작동 (0) | 2020.11.27 |
ASP.NET에서 버튼 태그를 어떻게 사용할 수 있습니까? (0) | 2020.11.27 |