injectJavaScript (ref 활용)

Column
Tags
inject
 
injectJavaScript 프롭도 제공하지만 이건 최초 로드 시에만 설정한 자바스크립트가 동작하는 단점이 있다.

대안

⇒ WebView 컴포넌트에 ref를 등록해서 사용하자.
 

함수형 컴포넌트에서 그냥 object를 통해 ref 관리 (이게 잘 됐었음)

import React from 'react'; import {View, TouchableOpacity, Text} from 'react-native'; import {WebView} from 'react-native-webview'; // WebViewProgressEvent import {NYTWebViewProps} from '@navigators/Stack/types'; export function NYTWebView({navigation, route}: NYTWebViewProps) { const uri = route.params.uri; console.log('fuck uri check : ', uri); // const wvRef = useRef(); const wvState = { canGoBack: false, ref: undefined, }; const onBackButtonPress = () => { if (wvState.ref && wvState.canGoBack) wvState.ref.injectJavaScript(goBackScript); else navigation.goBack(); }; const goBackScript = ` //alert("goBack()"+window.location.toString()); window.history.go(-1); true; `; navigation.setOptions({ headerLeft: () => ( <TouchableOpacity onPress={onBackButtonPress}> <Text>hi</Text> </TouchableOpacity> ), }); return ( <View style={{flex: 1}}> <WebView source={{ uri: 'https://www.nytimes.com/2021/11/28/business/uk-trucking-shortage-poland.html', }} javaScriptEnabled={true} ref={ref => (wvState.ref = ref)} onLoadProgress={e => (wvState.canGoBack = e.nativeEvent.canGoBack)} /> </View> ); }

함수형 컴포넌트에서 useRef() 활용

💡
아래 예시 코드는 퍼온건데, useRef()를 활용했던 건 잘 안됐었음
export default function App() { const wvRef = useRef(); return( <WebView source={{ uri: 'google.com' }} style={styles.container} scrollEnabled={false} javaScriptEnabled = {true} ref={wvRef} /> ); function test(){ let text = "123123"; wvREF.current.injectJavaScript(`(function(){ window.alert('`+text+`'); })(); `); }; }

ref 활용한 injectJavaScript 예시 ( 클래스 컴포넌트)

import React, { Component } from 'react'; import { View } from 'react-native'; import { WebView } from 'react-native-webview'; export default class App extends Component { render() { const run = ` document.body.style.backgroundColor = 'blue'; true; `; setTimeout(() => { this.webref.injectJavaScript(run); }, 3000); return ( <View style={{ flex: 1 }}> <WebView ref={(r) => (this.webref = r)} source={{ uri: 'https://github.com/react-native-community/react-native-webview', }} /> </View> ); } }
⇒ 이 스크립트는 3초 뒤에 배경색상을 파란색으로 변경시킨다.
notion image