본문 바로가기
모바일 앱/React Native

[React Native] WebView <img> click event 처리

by 테크케찰 2021. 7. 26.

react-native-webview 모듈을 이용해 html 소스를 앱에서 표시해주는 페이지를 개발하던 중, 이미지 클릭 시 이미지가 확대되도록 기능 구현을 해달라는 요청이 들어와 작업을 시작하였습니다.

 

<WebView 
    ...
    source={{
        html:changeHtmlTag(content)
    }}
    onMessage={event=>{
        console.log('onMessage Result, ', event.nativeEvent, typeof event.nativeEvent.data)
        if(checkImageUri(event.nativeEvent.data)){
            setPressedImageUri(event.nativeEvent.data);
        }
    }}
	...
/>
 const changeHtmlTag = (text) => {
    let newText = text.replace(/<img /g, '<img onclick="image(this)" ');

    return `
        <script>
            function image(img){
                // alert(img.src);
                // console.log('img after click', img);
                window.ReactNativeWebView.postMessage(img.src)
            }
        </script>
        ${newText}
    `;
  }
const checkImageUri=(uri)=>{
      return typeof uri==='string' && uri.includes('http');
  }

changeHtmlTag라는 함수를 보시면 기존 html 코드에서 img 태그 안에 onclick 함수를 추가해주는 것을 볼 수 있습니다.

클릭 시 실행되었을 때 image라는 함수를 불러오고 this라는 것을 파라미터로 넘겨주는데 여기서 this는 img 태그의 정보들(src 등)을 넘겨주는 것 같습니다.

추가로 기존 html 태그 앞에 <script> 태그에 감싸진 문장을 추가해주는 것을 보실 수 있습니다.

script 태그 내부를 보시면 window.ReactNativeWebview.postMessage() 란 문장이 있는데요, 이 명령어를 통해 WebView->React Native로 통신이 가능하다고 합니다.

위 문장을 통해 불러와진 값은 onMessage에서 event.nativeEvent.data를 통해 참조하실 수 있습니다

저는 checkImageUri린 함수를 정의해 유효성 검사를 했는데요, 파라미터의 값이 string 값이고, http 라는 문자열을 포함하는지를 검사해 checkImageUri가 통과된 경우에만 값을 참조할 수 있도록 설계했습니다.

 

이렇게 하시면 webview에서 이미지를 클릭하셨을 때 image의 주소 값을 onMessage를 통해 받아올 수 있고, 저는 받아온 값을 이용해 이미지를 확대하는 기능을 추가할 수 있었습니다.