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
반응형
'Javascript' 카테고리의 다른 글
Canvas Bubble Effect 기록(react + typescript) (0) | 2022.12.07 |
---|---|
Canvas Crash Effect 기록(react + typescript) (0) | 2022.12.07 |
[JS] URL 접속 QR code 만들기 (0) | 2021.11.30 |
[Vue js] dom drag move 돔 드래그로 이동시키기 (0) | 2021.11.11 |
[Vue js] 카카오 맵 api 로 현재위치 마커찍는 코드 (0) | 2021.11.10 |
댓글