React-Native
[React-Native] React native 와 WebView 데이터 통신 에러
방방방땡
2019. 6. 20. 13:28
React Native에서 WebView로 띄우고 데이터를 주고받는 작업에서 다른페이지는 괜찮았는데 KMC인증페이지를 호출하는데 계속 이러한 에러가 발생했다.
Setting onMessage on a WebView overrides existing values of window.postMessage, but a previous value was defined
특히 이놈이 안드로이드는 문제가 없는데 IOS에서만 계속 에러가났다..
알아보니 문제는 iOS에서 window.postMessage 호출을 연속적으로 수행 하면 마지막 호출이 성공할 때까지 메시지가 전달되기 전에 URL이 무시 될 때마다 첫 번째 호출이 손실 된다는 것
이 문제에 대해 수정은 여전히 진행되고 있는 중인것 같다.
일단 찾아서 해결한 방법은 이것이다.
해결방법
const patchPostMessageFunction = function() {
const originalPostMessage = window.postMessage;
const patchedPostMessage = function (message, targetOrigin, transfer) {
originalPostMessage(message, targetOrigin, transfer);
};
patchedPostMessage.toString = function() {
return String(Object.hasOwnProperty).replace('hasOwnProperty', 'postMessage');
};
window.postMessage = patchedPostMessage;
};
const patchPostMessageJsCode = '(' + String(patchPostMessageFunction) + ')();';
<WebView
source={{uri: "http://tictoccroc.com/ele/App_p/v2/join/v3_join_step_cert.php"}}
scrollEnabled={false}
// web 으로부터 메세지를 받아오는 함수
onMessage={(data)=>{
this.setState({postMessage: data.nativeEvent.data});
}}
injectedJavaScript={patchPostMessageJsCode}
/>
WebView 컴포넌트 안에있는 injectedJavaScript부분에 위에 작성한 patchPostMessageJsCode를 삽입해주면 해결완료