简体   繁体   中英

How can i pass data from react-native to react-native-webview?

I am trying to get a token from Firebase and pass the token to the webview.

The blog says to use webviewRef.current.postMessage, but that function is not executed. How can I pass the token?

Below is my code.

    const App = () => {
    useEffect(() => {
        const firebase = async () => {
        try {
           const token = await messaging().getToken();  // i want to pass this token to webview
        } catch (error) {
        }
        };

        firebase();
    }, []);

    return (
        <SafeAreaView style={{flex: 1}}>
        <WebView
            startInLoadingState={true}
            source={{uri: 'http://myurl'}}
        />
        </SafeAreaView>
    );
    };

Use can pass data to web-view from react-native by using injectJavascript method like the code below. Ref https://github.com/react-native-webview/react-native-webview/blob/4c050771757f4f7d92cf816bf0a5bf16c5539c07/docs/Reference.md#injectjavascriptstr

import React, { useRef } from 'react';
import { WebView } from 'react-native-webview';

const MyWebView = (props) => {
  const webviewRef = useRef(null);

  const injectedJavaScript = `
    function setData(data) {
      window.data = data;
    }
  `;

  return (
    <WebView
      source={{ uri: 'https://example.com' }}
      injectedJavaScript={injectedJavaScript}
      onLoad={() => {
        webviewRef.current.injectJavaScript(`setData(${JSON.stringify(props.data)});`);
      }}
      ref={webviewRef}
    />
  );
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM