Web APIs

Frontend SELF KO
레벨 46 , 레슨 2
사용 가능

7.1 Geolocation API

Web APIs (Web Application Programming Interfaces)는 웹 애플리케이션이 브라우저 및 사용자 장치의 기능과 상호작용할 수 있는 강력한 기능을 제공합니다. 여기에서는 GeolocationNotifications를 포함한 일부 API와 그 사용법을 살펴보겠습니다.

Geolocation API는 웹 애플리케이션이 사용자의 장치 위치 정보를 얻을 수 있게 해줘요. 지도, 내비게이션, 지역 타겟팅 같은 다양한 애플리케이션에 유용할 수 있죠.

위치 접근 권한 요청

Geolocation API를 사용하려면, 웹 애플리케이션이 사용자에게 위치 정보 접근 권한을 요청해야 해요. 이는 navigator.geolocation.getCurrentPosition() 메서드를 통해 이루어집니다.

Geolocation API 사용 예시:

JavaScript
    
      if ('geolocation' in navigator) {
        navigator.geolocation.getCurrentPosition(
          (position) => {
            const { latitude, longitude } = position.coords;
            console.log(`위도: ${latitude}, 경도: ${longitude}`);
          },
          (error) => {
            console.error('지리 정보 가져오기 오류:', error);
          },
          {
            enableHighAccuracy: true, // 높은 정확도
            timeout: 5000, // 응답 대기 시간 (ms)
            maximumAge: 0 // 캐시된 데이터를 사용할 수 있는 최대 시간 (ms)
          }
        );
      } else {
        console.log('이 브라우저에서는 Geolocation을 지원하지 않습니다.');
      }
    
  

위치 추적

navigator.geolocation.watchPosition() 메서드는 사용자의 위치 변화를 추적할 수 있게 해줍니다.

위치 추적 예시:

JavaScript
    
      let watchId;

      if ('geolocation' in navigator) {
        watchId = navigator.geolocation.watchPosition(
          (position) => {
            const { latitude, longitude } = position.coords;
            console.log(`위도: ${latitude}, 경도: ${longitude}`);
          },
          (error) => {
            console.error('지리 정보 가져오기 오류:', error);
          },
          {
            enableHighAccuracy: true,
            timeout: 5000,
            maximumAge: 0
          }
        );
      }

      // 위치 추적 중지
      function stopTracking() {
        if (watchId) {
          navigator.geolocation.clearWatch(watchId);
        }
      }
    
  

7.2 Notifications API

Notifications API는 웹 애플리케이션이 사용자 시스템에 알림을 표시할 수 있게 해줘요. 브라우저 탭이 비활성 상태일 때도 중요한 이벤트에 대해 사용자의 관심을 끌기 위해 유용하죠.

알림 전송 권한 요청

Notifications API를 사용하려면 웹 애플리케이션이 사용자에게 알림 전송 권한을 요청해야 해요.

권한 요청 예시:

JavaScript
    
      if ('Notification' in window) {
        Notification.requestPermission().then((permission) => {
          if (permission === 'granted') {
            console.log('알림 권한이 부여되었습니다.');
          } else {
            console.log('알림 권한이 거부되었습니다.');
          }
        });
      } else {
        console.log('이 브라우저에서는 알림을 지원하지 않습니다.');
      }
    
  

알림 전송

권한을 받은 후에는 Notification 생성자를 사용하여 알림을 보낼 수 있어요.

알림 전송 예시:

JavaScript
    
      if (Notification.permission === 'granted') {
        const options = {
          body: '이것은 알림 본문입니다',
          icon: 'icon.png',
          data: { url: 'https://example.com' }
        };
        const notification = new Notification('안녕하세요, 세상!', options);

        // 알림 클릭 처리
        notification.onclick = (event) => {
          event.preventDefault(); // 기본 이동 방지
          window.open(notification.data.url, '_blank');
        };
      }
    
  

7.3 다른 유용한 Web API

1. DeviceOrientation API

DeviceOrientation API는 장치의 공간적 위치 데이터를 제공해요.

DeviceOrientation API 사용 예시:

JavaScript
    
      window.addEventListener('deviceorientation', (event) => {
        console.log(`알파: ${event.alpha}, 베타: ${event.beta}, 감마: ${event.gamma}`);
      });
    
  

2. Battery Status API

Battery Status API는 장치의 배터리 상태에 대한 정보를 제공합니다.

Battery Status API 사용 예시:

JavaScript
    
      navigator.getBattery().then((battery) => {
        console.log(`배터리 수준: ${battery.level * 100}%`);
        console.log(`배터리 충전 중: ${battery.charging}`);

        battery.addEventListener('levelchange', () => {
          console.log(`배터리 수준 변경됨: ${battery.level * 100}%`);
        });

        battery.addEventListener('chargingchange', () => {
          console.log(`배터리 충전 상태 변경됨: ${battery.charging}`);
        });
      });
    
  

3. Fullscreen API

Fullscreen API는 웹 페이지를 전체 화면 모드로 전환할 수 있게 해줍니다.

Fullscreen API 사용 예시:

JavaScript
    
      const element = document.documentElement; // 전체 문서

      function toggleFullScreen() {
        if (!document.fullscreenElement) {
          element.requestFullscreen().catch((err) => {
            console.error(`전체 화면 모드 활성화 시도 중 오류 발생: ${err.message}`);
          });
        } else {
          document.exitFullscreen();
        }
      }

      document.getElementById('fullscreenButton').addEventListener('click', toggleFullScreen);
    
  
코멘트
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION