JavaScript 치트시트
13. 브라우저 API
13.1 LocalStorage / SessionStorage
// LocalStorage
localStorage.setItem('name', 'Alice');
console.log(localStorage.getItem('name'));
localStorage.removeItem('name');
// SessionStorage
sessionStorage.setItem('sessionId', '12345');
console.log(sessionStorage.getItem('sessionId'));
sessionStorage.clear();
13.2 Cookie 처리
// 쿠키 생성
document.cookie = 'username=Alice; expires=Fri, 31 Dec 2025 23:59:59 GMT; path=/';
console.log(document.cookie);
13.3 Fetch / XMLHttpRequest
// Fetch API
fetch('https://jsonplaceholder.typicode.com/posts/1')
.then(response => response.json())
.then(data => console.log(data))
.catch(err => console.error(err));
// XMLHttpRequest
const xhr = new XMLHttpRequest();
xhr.open('GET', 'https://jsonplaceholder.typicode.com/posts/1');
xhr.onload = () => console.log(JSON.parse(xhr.responseText));
xhr.send();
13.4 WebSocket
const socket = new WebSocket('wss://echo.websocket.org');
socket.onopen = () => socket.send('Hello WebSocket');
socket.onmessage = event => console.log('받은 메시지:', event.data);
13.5 Geolocation
navigator.geolocation.getCurrentPosition(
position => console.log(position.coords.latitude, position.coords.longitude),
error => console.error(error)
);
13.6 Canvas API
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');
ctx.fillStyle = 'red';
ctx.fillRect(10, 10, 100, 50);
ctx.strokeStyle = 'blue';
ctx.strokeRect(20, 20, 80, 30);
13.7 History / Location / Navigator
// History
console.log(history.length);
history.back();
history.forward();
// Location
console.log(location.href);
// Navigator
console.log(navigator.userAgent);