JavaScript:如何檢測網站是在移動裝置還是桌面裝置上開啟的?


我們可以使用CSS媒體查詢來檢查網站是開啟在 Web 瀏覽器中還是移動瀏覽器中。此資訊可以使用網頁的最小寬度和最大寬度獲取。

CSS媒體查詢僅限於對網頁進行樣式設定,但我們可以使用 JavaScript 中的 navigator 屬性來根據使用者的裝置控制網站的功能。

Navigator 返回一組值,其中包括使用者瀏覽器、版本、作業系統等等。

語法

navigator.userAgent

示例

在下面的示例中,我們將使用 Navigator 獲取使用者的裝置詳細資訊。這將獲得主要資訊,其中包括使用者瀏覽器、版本、作業系統等。

# index.html

<!DOCTYPE html>
<html>
<head>
   <title>Filtering the Non-unique characters</title>
</head>
<body>
   <h1 style="color: green;">
      Welcome To Tutorials Point
   </h1>
   <script>
      /* Storing user's device details in a variable*/
      let details = navigator.userAgent;
      
      /* Creating a regular expression
      containing some mobile devices keywords
      to search it in details string*/
      let regexp = /android|iphone|kindle|ipad/i;
      
      /* Using test() method to search regexp in details
      it returns boolean value*/
      let isMobileDevice = regexp.test(details);
      
      if (isMobileDevice) {
         document.write("<h3>Its a Mobile Device !</h3>");
      } else {
         document.write("<h3>Its a Desktop !</h3>");
      }
   </script>
</body>
</html>

輸出

當該網頁在桌面上開啟時 −

當該網頁在移動裝置上開啟時 −

更新日期:2022 年 4 月 26 日

8,000+ 次檢視

開啟你的 職業生涯

完成課程獲得認證

開始
廣告