How to get json data in react native from web-view

 How  to get body content json data in  react-native from web-view


Hi Developer, 

are you looking answer to get json data from Web-View to React Native App (State or Variable)


i have that issue solution:

See this code :
  import React, { useRef, useState } from 'react';
import { View, Text, Alert } from 'react-native';
import WebView from 'react-native-webview';

const Screen2 = () => {
  const [content, setContent] = useState('');

  const webviewRef = useRef(null);

  const handleNavigationChange = (navState) => {
    // console.log('Navigation State Change:', navState);
  
    // Check if the WebView has navigated to the specific URL
    if (navState.url === 'http://ip.jsontest.com/') {
      // Inject JavaScript to extract JSON data from the response body
      const script = `
        const bodyContent = document.body.textContent;
        try {
          const jsonData = JSON.parse(bodyContent);
          window.ReactNativeWebView.postMessage(JSON.stringify(jsonData));
        } catch (error) {
          console.error('JSON Parsing Error:', error);
          window.ReactNativeWebView.postMessage(JSON.stringify({ error: error.message }));
        }
      `;
      webviewRef.current.injectJavaScript(script);
    }
  };
  

  const handleMessage = (event) => {
    const extractedContent = event.nativeEvent.data;
    // console.log(extractedContent)
    Alert.alert("Data Got:", extractedContent)
    setContent(extractedContent);
  };

  return (
   
    
      Hello
      
        
      
   
     
    
 
  );
};

export default Screen2;

  
here have view code You can see here fetch data logs:
  
   LOG  {"ip":"2409:4064:4d9c:8ac9::a5cb:3209"}
  
you have to paas like this in web view :

ref={webviewRef} javaScriptEnabled={true} // Ensure JavaScript is enabled source={{ uri: 'https://www.jsontest.com/' }} onNavigationStateChange={handleNavigationChange} onMessage={handleMessage}

Comments

Popular posts from this blog

how to get 1,000 rupya by Bihar government immediately || in Hindi||covid19

How to get 1000 rupya by Bihar VIP party in Hindi

10th class scholarship10 बिहार के छात्रों के लिए