본문 바로가기
Javascript

React Native WebView postMessage로 네이티브, 웹 데이터 전달

by YoYoHa 2022. 3. 29.
728x90
반응형

React Native

npm install react-native-webview
import React, { useRef } from "react";
import {WebView} from 'react-native-webview';
import { Button, SafeAreaView } from "react-native";

const App = () => {

  const url = "URL"
  let webRef = useRef<WebView>(null);

  /** 웹뷰 ref */
  const handleSetRef = _ref => {
    webRef = _ref;
  };

  /* native -> web */
  const native_to_web = () => {
    console.log(webRef.postMessage("전송 데이터(React) : 웹으로 데이터 전송"));
  }

  const errorHandler = ({nativeEvent}) => console.warn("WebView error: ", nativeEvent);

  /* web -> native */
  const web_to_native = (e) => {
    console.log(e.nativeEvent.data);
  }

  return (
    <SafeAreaView style={{flex:1}}>
      <Button title={'postMessage'} onPress={native_to_web} />
      <WebView
        ref={handleSetRef}
        source={{ uri: url }}
        javaScriptEnabled={true}
        onLoad={native_to_web}
        onError={errorHandler}
        onMessage={(event) => {
          console.log("받은 데이터(React) : " + event.nativeEvent.data);
        }}
      />
    </SafeAreaView>
  );
};

export default App;

 

Web(Vue js)

<template>
  <div>
    <div v-on:click="btn">Native로 데이터 전송</div>
  </div>
</template>

<script>
export default {
  name: 'Home',
  methods:{

    btn(){
      this.sendMessage("전송 데이터(Web) : 네이티브로 데이터 전송");
    },

    sendMessage(str){
      window.ReactNativeWebView.postMessage(str);
    },

    receiveMessage(event){
      alert("받은 데이터(Web) : "+event.data);
      this.postMessage = event.data;
    }
  },
  mounted(){

    const varUA = navigator.userAgent.toLowerCase(); //userAgent 값 얻기

    if ( varUA.indexOf('android') > -1) {
      /** android */
      document.addEventListener("message", this.receiveMessage);
      this.sendMessage('Android 핸드폰으로 웹 접속');
    } else if ( varUA.indexOf("iphone") > -1||varUA.indexOf("ipad") > -1||varUA.indexOf("ipod") > -1 ) {
      /** ios */
      window.addEventListener("message", this.receiveMessage);
      this.sendMessage('iOS 핸드폰으로 웹 접속');
    }
  }
}
</script>
<style scoped>

</style>
728x90
반응형

댓글