웹과 앱은 화면 전환 구조가 다르다.
<aside> 👉
따라서 일관된 사용자 경험(UX)을 위해 앱과 웹 간의 화면 전환 구조를 통일하는 것이 중요하다.
</aside>
React Native WebView에서는 postMessage()를 사용하여 데이터를 웹으로 전송할 수 있다.
// 웹에게 데이터 전송
const message = { type: "kakaoInfo", value: { email, id, nickname };
if (webiViewRef.current) {
webViewRef.current.postMessage(JSON.stringify(message));
}
postMessage()는 Window 객체 사이에서 안전하게 cross-origin 통신을 가능하게 해준다.웹에서는 메시지 핸들러를 등록해 데이터를 수신할 수 있다.
useEffect(() => {
const handleMessage = async (event: MessageEvent) => {
const { type, value } = JSON.parse(event.data);
if (type === 'openPostWrite') {
// 게시물 쓰기 페이지 이동
if (loginStatus) {
sendRouterEvent(`${SERVICE_URL.communityWrite}`);
}
}
if (type === 'kakaoInfo') {
// 중략
}
};
// android 이벤트 캐치
document.addEventListener('message', handleMessage);
// ios 이벤트 캐치
window.addEventListener('message', handleMessage);
return () => {
window.removeEventListener('message', handleMessage);
};
}, []);
웹은 window.ReactNativeWebView.postMessage()를 이용해 앱으로 메시지를 전달할 수 있다.
export const sendRouterEvent = (path: string): void => {
window.ReactNativeWebView.postMessage(
JSON.stringify({ type: 'ROUTER_EVENT', path })
);
};