본문 바로가기
카테고리 없음

PC, Mobile 자바스크립트로 디바이스 구분

by 경험을 기록하다. 2024. 12. 29.

데스크탑(PC) 환경에서

 
    window.onload = function () {
      function isMobile() {
        const userAgent = navigator.userAgent.toLowerCase();
        return /android|iphone|ipad|ipod|blackberry|iemobile|opera mini|webos/i.test(userAgent);
      }

      function isPC() {
        const userAgent = navigator.userAgent.toLowerCase();
        return !isMobile() && /windows|macintosh|linux/i.test(userAgent);
      }

      const isOnMobilePage = window.location.href.includes('m.html');
      const isOnindexPage = window.location.href.includes('index.html');
      console.log(isOnMobilePage, "isOnMobilePage")
      console.log(isOnindexPage, "isOnindexPage")

      // 리다이렉트 로직
      if (isMobile() && !isOnMobilePage) {
        // 모바일 환경에서 모바일 페이지로 리다이렉트
        window.location.href = './m.html';
        console.log("모바일 환경에서 모바일 페이지로 리다이렉트")
      }
     
      if (isPC() && !isOnindexPage) {
        // PC 환경에서 모바일 페이지 리다이렉트
        window.location.href = './index.html';
        console.log("PC 환경에서 모바일 페이지 리다이렉트");
      } else {
        console.log("Unknown device, staying on this page.");
      }
    }
 

모바일 환경에서

 
    window.onload = function () {
      function isMobile() {
        const userAgent = navigator.userAgent.toLowerCase();
        return /android|iphone|ipad|ipod|blackberry|iemobile|opera mini|webos/i.test(userAgent);
      }

      function isPC() {
        const userAgent = navigator.userAgent.toLowerCase();
        return !isMobile() && /windows|macintosh|linux/i.test(userAgent);
      }

      const isOnMobilePage = window.location.href.includes('m.html');
      const isOnindexPage = window.location.href.includes('index.html');

      console.log(isOnMobilePage, "isOnMobilePage")
      console.log(isOnindexPage, "isOnindexPage")
      // 리다이렉트 로직
      if (isMobile() && !isOnMobilePage) {
        // 모바일 환경에서 모바일 페이지로 리다이렉트
        console.log("모ㅇㄴㄹㄴㅇㄹPC 환경에서 모바일 페이지 접속");
        window.location.href = './index.html';
      }
     
      if (isPC() && isOnindexPage) {
        console.log("모ㅇㄴㄹㄴㅇㄹPC 환경에서 모바일 페이지 접속");
        window.location.href = './m.html';
      } else {
        console.log("Unknown device, staying on this page.");
      }
    }