JavaScript Web API


자바스크립트의 웹 API(Web API)는 웹 애플리케이션에서 브라우저와 상호작용하거나 웹 서버와 데이터를 교환하기 위해 제공되는 다양한 기능의 집합입니다. 웹 API는 브라우저 내장 기능을 확장하거나 웹 애플리케이션이 외부 리소스와 상호작용할 수 있도록 해줍니다.

웹 API는 보통 자바스크립트에서 사용되며, 브라우저 환경에서 다양한 작업을 수행할 수 있도록 도와줍니다. 웹 API는 주로 DOM API, 브라우저 API, 서버 API 등으로 구분할 수 있습니다.

1. DOM API

DOM API는 HTML 문서의 구조를 조작하고 접근하기 위한 인터페이스를 제공합니다.

1.1 document 객체

  • document.getElementById(id): 특정 ID를 가진 요소를 반환합니다.
  • document.querySelector(selector): CSS 선택자와 일치하는 첫 번째 요소를 반환합니다.
  • document.createElement(tagName): 새로운 HTML 요소를 생성합니다.
  • document.createTextNode(text): 새로운 텍스트 노드를 생성합니다.
// 예시
const element = document.getElementById('myId');
const newElement = document.createElement('div');
newElement.textContent = 'Hello, world!';
document.body.appendChild(newElement);

1.2 Element 객체

  • element.innerHTML: 요소의 HTML 내용을 설정하거나 반환합니다.
  • element.setAttribute(name, value): 요소의 속성을 설정합니다.
  • element.classList: 요소의 클래스를 조작합니다.
// 예시
const element = document.getElementById('myElement');
element.innerHTML = '<p>New content</p>';
element.setAttribute('data-info', 'some data');
element.classList.add('new-class');

2. 브라우저 API

브라우저 API는 브라우저의 기능을 제어하거나 사용자의 상호작용을 처리하는 기능을 제공합니다.

2.1 fetch API

fetch API는 네트워크 요청을 수행하고 응답을 처리할 수 있는 기능을 제공합니다. 주로 HTTP 요청을 보내고 응답을 받는 데 사용됩니다.

// 예시
fetch('https://api.example.com/data')
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error('Error:', error));

2.2 localStoragesessionStorage

localStoragesessionStorage는 클라이언트 측에 데이터를 저장할 수 있는 방법을 제공합니다.

  • localStorage: 브라우저가 닫혀도 데이터가 유지됩니다.
  • sessionStorage: 브라우저 탭이 닫히면 데이터가 삭제됩니다.
// 예시
localStorage.setItem('key', 'value');
const value = localStorage.getItem('key');
localStorage.removeItem('key');

sessionStorage.setItem('key', 'value');
const sessionValue = sessionStorage.getItem('key');
sessionStorage.removeItem('key');

2.3 WebSocket

WebSocket API는 클라이언트와 서버 간의 양방향 통신을 가능하게 합니다.

// 예시
const socket = new WebSocket('ws://example.com/socket');

socket.onopen = function(event) {
  console.log('WebSocket connection opened');
  socket.send('Hello Server!');
};

socket.onmessage = function(event) {
  console.log('Message from server:', event.data);
};

socket.onclose = function(event) {
  console.log('WebSocket connection closed');
};

socket.onerror = function(error) {
  console.error('WebSocket error:', error);
};

2.4 Geolocation API

Geolocation API는 사용자의 위치 정보를 가져올 수 있습니다.

// 예시
navigator.geolocation.getCurrentPosition(function(position) {
  console.log('Latitude:', position.coords.latitude);
  console.log('Longitude:', position.coords.longitude);
}, function(error) {
  console.error('Error occurred:', error);
});

2.5 Notification API

Notification API는 브라우저에서 사용자에게 알림을 보내는 기능을 제공합니다.

// 예시
if (Notification.permission === 'granted') {
  new Notification('Hello World!', {
    body: 'This is a notification message.',
    icon: 'icon.png'
  });
} else if (Notification.permission !== 'denied') {
  Notification.requestPermission().then(permission => {
    if (permission === 'granted') {
      new Notification('Hello World!', {
        body: 'This is a notification message.',
        icon: 'icon.png'
      });
    }
  });
}

3. 서버 API

서버 API는 주로 웹 애플리케이션이 서버와 상호작용하는 데 사용됩니다. 브라우저와 서버 간의 데이터 통신을 처리합니다.

3.1 XMLHttpRequest

XMLHttpRequest는 비동기 HTTP 요청을 보내고 응답을 받을 수 있는 오래된 방법입니다. fetch API가 더 많이 사용되지만, 여전히 지원됩니다.

// 예시
const xhr = new XMLHttpRequest();
xhr.open('GET', 'https://api.example.com/data', true);

xhr.onload = function() {
  if (xhr.status === 200) {
    console.log(xhr.responseText);
  } else {
    console.error('Request failed');
  }
};

xhr.onerror = function() {
  console.error('Request error');
};

xhr.send();

4. HTML5 및 기타 API

4.1 Canvas API

Canvas API는 2D 그래픽을 그릴 수 있는 기능을 제공합니다.

// 예시
const canvas = document.getElementById('myCanvas');
const context = canvas.getContext('2d');

context.fillStyle = 'blue';
context.fillRect(10, 10, 100, 100);

4.2 Audio API

Audio API는 웹 애플리케이션에서 오디오를 생성하고 조작할 수 있게 합니다.

// 예시
const audio = new Audio('audio.mp3');
audio.play();

4.3 WebRTC

WebRTC는 브라우저 간의 실시간 오디오 및 비디오 통신을 가능하게 합니다.

// 예시
navigator.mediaDevices.getUserMedia({ video: true, audio: true })
  .then(stream => {
    document.getElementById('videoElement').srcObject = stream;
  })
  .catch(error => {
    console.error('Error accessing media devices:', error);
  });

5. 커스텀 웹 API

자바스크립트에서 커스텀 웹 API를 정의하여 웹 애플리케이션의 특정 기능을 구현할 수 있습니다.

5.1 API 설계

  • 엔드포인트 정의: API의 경로 및 기능을 정의합니다.
  • 요청 처리: 요청에 대해 적절한 응답을 반환합니다.
  • 응답 형식: JSON, XML 등의 형식으로 응답을 제공합니다.
// 예시: Express.js를 사용한 간단한 API
const express = require('express');
const app = express();

app.get('/api/greet', (req, res) => {
  res.json({ message: 'Hello, World!' });
});

app.listen(3000, () => {
  console.log('Server is running on port 3000');
});

결론

자바스크립트의 웹 API는 웹 애플리케이션에서 다양한 기능을 구현할 수 있는 강력한 도구입니다. DOM API를 통해 웹 페이지를 조작하고, 브라우저 API를 통해 다양한 기능을 활용하며, 서버 API를 통해 서버와 상호작용할 수 있습니다. 이러한 API를 적절히 활용하면 풍부하고 동적인 웹 애플리케이션을 개발할 수 있습니다.


Leave a Reply

Your email address will not be published. Required fields are marked *