'How to get the html source of WebView object in react native

I'm trying to access the HTML source code of a 3rd party web page to read a specific DOM element value of a page which is loaded in WebView component in react-native.

<WebView
        source={{uri: 'https://www.amazon.com'}}
      />

and Suppose there's a DOM element like this:

<span class="price bold some-class-name">$459.00</span>

I also tried this component but could not do that: https://github.com/alinz/react-native-webview-bridge

Is there any way to get the current HTML source code of page inside a WebView and Read specific DOM element value?



Solution 1:[1]

The answer by Brian F is great and helped me a lot. There is just one thing missing. You need to append ReactNativeWebView to the postMessage function.

So it would look like

render (
  const jsCode = "window.ReactNativeWebView.postMessage(document.getElementsByClassName("price bold some-class-name"))"

  return (
     <View style={styles.container}>
         <WebView
             source={{uri: "http://..."}}
             onMessage={this._onMessage}
             injectedJavaScript={jsCode}
         />
     </View>
  );
)

Solution 2:[2]

In my experience, It will work well, because I've tried to get product information from Amazon and Taobao, Rakuten.

_onMessage = (message) => {
  // you can put processing code here.
}


render (
      const jsCode = "window.ReactNativeWebView.postMessage(document.getElementsByClassName("class name"))"
      // or you can use `document.querySelector("element query")` instead of `document.getElementsByClassName("class name")`
    
      return (
         <View style={styles.container}>
             <WebView
                 source={{uri: "url here"}}
                 onMessage={this._onMessage}
                 injectedJavaScript={jsCode}
             />
         </View>
      );
    )

Solution 3:[3]

For those who are still not getting then try this for the latest react-native

    window.ReactNativeWebView.postMessage(document.getElementById('id_here').innerHTML);

const INJECT_JS = `window.ReactNativeWebView.postMessage(document.getElementById('id_here').innerHTML);
alert("Hel0....")
`

  return (
     <View style={styles.container}>
         <WebView
             source={{uri: "http://..."}}
         onMessage={event => {
          console.log(event.nativeEvent.data);
        }}
             injectedJavaScript={INJECT_JS }
         />
     </View>
  );

Solution 4:[4]

<WebView
    source={{html: "<span class="price bold some-class-name">$459.00</span>"
/>

or you can right your template into a constant, then do this:

const HTMLTemplate = `<span class="price bold some-class-name">$459.00</span>`;

<WebView
    source={{html: HTMLTemplate}}
/>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 hytea
Solution 2 Rovert Jonybal
Solution 3 JASIM TK
Solution 4 KATHERINE