← 홈으로 돌아가기

쿠키/스토리지

웹 세션 및 데이터 관리

🍪 쿠키 관리

쿠키 설정

// Vue/React에서
await bridge.setCookie('session_id', 'abc123', {
  domain: '.example.com',
  path: '/',
  maxAge: 86400,  // 1일
  secure: true,
  httpOnly: true
});

Flutter 구현

final cookieManager = WebViewCookieManager();

await cookieManager.setCookie(
  WebViewCookie(
    name: 'session_id',
    value: 'abc123',
    domain: '.example.com',
    path: '/',
  ),
);

쿠키 읽기

// JavaScript
const cookies = document.cookie
  .split(';')
  .reduce((acc, cookie) => {
    const [name, value] = cookie.trim().split('=');
    acc[name] = value;
    return acc;
  }, {});

💾 로컬 스토리지

데이터 저장

// Vue/React
await bridge.saveData('user', {
  id: 123,
  name: 'John',
  email: 'john@example.com'
});

Flutter SharedPreferences

final prefs = await SharedPreferences.getInstance();
await prefs.setString('user', jsonEncode(userData));

데이터 불러오기

const user = await bridge.loadData('user');
console.log(user.name); // 'John'

🔄 세션 스토리지

JavaScript 실행

// Flutter에서 JavaScript 실행
await _controller.runJavaScript('''
  sessionStorage.setItem('temp_data', JSON.stringify({
    timestamp: Date.now()
  }));
''');

읽기

final result = await _controller.runJavaScriptReturningResult('''
  sessionStorage.getItem('temp_data')
''');
print(result);

🔐 보안 저장소

FlutterSecureStorage

민감한 데이터(토큰, 비밀번호 등)는 암호화된 저장소에:

final storage = FlutterSecureStorage();

// 저장
await storage.write(key: 'auth_token', value: token);

// 읽기
final token = await storage.read(key: 'auth_token');

// 삭제
await storage.delete(key: 'auth_token');

🔗 웹뷰 연동

WebView → Flutter

// WebView의 localStorage를 Flutter로
await _controller.runJavaScriptReturningResult('''
  JSON.stringify(localStorage)
''').then((value) async {
  final data = jsonDecode(value);
  final prefs = await SharedPreferences.getInstance();
  await prefs.setString('webview_storage', value);
});

Flutter → WebView

// Flutter의 데이터를 WebView로
final prefs = await SharedPreferences.getInstance();
final data = prefs.getString('app_data');

await _controller.runJavaScript('''
  const data = ${jsonEncode(data)};
  localStorage.setItem('app_data', JSON.stringify(data));
''');

📊 데이터 동기화

양방향 동기화

// 1. WebView → Flutter 저장
case 'SAVE_DATA':
  final key = payload['key'];
  final value = payload['value'];
  final prefs = await SharedPreferences.getInstance();
  await prefs.setString(key, jsonEncode(value));
  break;

// 2. Flutter → WebView 전송
await _controller.runJavaScript('''
  window.dispatchEvent(new CustomEvent('storage-sync', {
    detail: { key: '$key', value: $valueJson }
  }));
''');

🎯 실전 예제

인증 토큰 관리

// 로그인 후
const token = 'eyJhbGciOiJIUzI1NiIs...';

// 보안 저장
await bridge.saveSecure('auth_token', token);

// API 호출 시 사용
const token = await bridge.loadSecure('auth_token');
fetch('/api/user', {
  headers: { 'Authorization': `Bearer ${token}` }
});

오프라인 데이터

// 온라인일 때 저장
const posts = await fetchPosts();
await bridge.saveData('cached_posts', posts);

// 오프라인일 때
if (!navigator.onLine) {
  const posts = await bridge.loadData('cached_posts');
  displayPosts(posts);
}

⚠️ 주의사항

💡 베스트 프랙티스

안전한 데이터 관리로 사용자 개인정보를 보호하세요!