웹뷰(webView)는 모바일 애플리케이션 내에서 웹 콘텐츠를 표시하기 위한 컴포넌트이다.
앱 한계 때문에 웹뷰를 종종 사용하곤 하는데..
웹뷰를 사용할 때 주로 사용되는 상호 작용 메커니즘으로 injectJavaScript, postMessage를 사용한다!
injectJavaScript: Javascript코드를 webView로 주입해서 실행하는 것으로,
웹뷰 안의 Javascript 코드를 동적으로 실행할 수 있다.
WebView 내에서 수행할 작업을 제어하거나 변경하기 위해 사용한다.
postMessage: 웹뷰와 RN간의 통신을 가능하게 하는 메서드이다.
WebView에서 postMessage를 호출하여 데이터를 전달하고,
앱은 WebView의 onMessage 이벤트를 통해 해당 메시지를 수신할 수 있다.
webView 컴포넌트의 OnMessage 속성은 웹에서 postMessage를 통해 데이터를 전달했을 때 실행되는 콜백함수를 정의할 수 있다.
import React from "react";
import { WebView } from "react-native-webview";
const WebView = () => {
//데이터를 받을 때 사용
const handleOnMessage = (e) => {
console.log(e.nativeEvent.data);
};
// RN -> 웹뷰로 데이터를 보낼 때 사용
const sendMessage = () => {
const sendData =JSON.stringify({
company:"주식회사",
id:1,
name:"testName",
phone:"01011112222",
});
webViewRef.current.postMessage(sendData);
}
return (
<View>
<WebView
onMessage={handleOnMessage}
source={"http://localhost:8000"}
/>
<TouchableOpacity onPress={sendMessage}>
<Text>WebView</Text>
</TouchableOpacity>
</View>
);
};
export default WebView;
window.ReactNativeWebview 객체에는 postMessage라는 메서드가 있다.
이 메서드를 사용하여 RN으로 데이터를 보낼 수 있다.
앱에서 데이터를 전송하면, 웹에서는 addEventListener("message")를 통해서 해당 메시지를 받을 수 있다.
useEffect(() => {
// RN -> 웹으로 데이터를 전송했을때 message 이벤트가 실행됨
document.addEventListener("message", (e) => {
alert(e.data);
})
}, []);
// 웹뷰 -> RN으로 데이터를 보낼 때 사용
const sendToRN = () => {
if (window.ReactNativeWebView) {
// RN에서 데이터는 문자열로 받을 수 있기 때문에 JSON.stringify를 사용
window.ReactNativeWebView.postMessage(
JSON.stringify( {data:"hello"} )
);
} else {
//예외 처리
}
};