JavaScript browser detection: a simple and effective solution
In the development of web pages, detecting the user's browser type is very helpful for processing the browser's specific bug, application compatibility repair or optimization performance. Although modern development advocates characteristic detection rather than browser detection, it is still practical to understand the browser used by users. This article will explore a simple and effective JavaScript method, using
attributes to detect different browsers. navigator.userAgent
window.navigator.userAgent
For example:
From this we can extract useful information. For example, users use Chrome, Safari or other browsers.
<code>Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/110.0.0.0 Safari/537.36</code>
The following is a simple way to use JavaScript to detect browsers:
Code detailed explanation
<code class="language-javascript">const userAgent = window.navigator.userAgent; const isEdge = /Edge/.test(userAgent); // 检测Microsoft Edge const isChrome = /chrome/i.test(userAgent) && !isEdge; // 检测Chrome,排除Edge const isSafari = /safari/i.test(userAgent) && !isEdge; // 检测Safari,排除Edge const isMobile = /mobile/i.test(userAgent); // 检测移动设备 const isIEWin7 = /Windows NT 6.1/i.test(userAgent) && /rv:11/i.test(userAgent); // 检测Windows 7上的Internet Explorer 11 const isOldSafari = isSafari && (/Version\/8/i.test(userAgent) || /Version\/9/i.test(userAgent)); // 检测旧版Safari const isEnabledForBrowser = (isChrome || isSafari || isIEWin7) && !isMobile;</code>
<code class="language-javascript">const isEdge = /Edge/.test(userAgent);</code>
<code class="language-javascript">const isChrome = /chrome/i.test(userAgent) && !isEdge;</code>
<code class="language-javascript">const isSafari = /safari/i.test(userAgent) && !isEdge;</code>
Mobile browser usually contains "Mobile" in its USARAGENT.
<code class="language-javascript">const isMobile = /mobile/i.test(userAgent);</code>
The USRAGENT of Windows 7 contains "Windows NT 6.1", and IE 11 contains "RV: 11".
<code class="language-javascript">const isIEWin7 = /Windows NT 6.1/i.test(userAgent) && /rv:11/i.test(userAgent);</code>
<code class="language-javascript">const isOldSafari = isSafari && (/Version\/8/i.test(userAgent) || /Version\/9/i.test(userAgent));</code>
Full code example
The above is the detailed content of Detecting Browsers in JavaScript. For more information, please follow other related articles on the PHP Chinese website!