DEV Community

Discussion on: WebView — Navigation and data flow with WebViews in a React Native app

Collapse
 
digitlninja profile image
digitalninja • Edited

Hey man, great article. Ive tried to get data from RN to my WebApp but am not winning.
Where did you add the eventListener exactly?

Heres my gist
gist.github.com/digitlninja/fd4dea...

Collapse
 
mukeshmandiwal profile image
Mukesh Mandiwal • Edited

/* 
Sample data you want to pass from react  native to web 
*/

const runFirst = `
      document.body.style.backgroundColor = 'green';
      setTimeout(function() { window.alert(JSON.stringify([
             'Javascript',
             'React',
             'React Naitve',
             'graphql',
             'Typescript',
             'Webpack',
             'Node js',
          ])) }, 1000);
      true; // note: this is required, or you'll sometimes get silent failures
    `;

<WebView 
 source={{ uri: 'http://localhost:3000' }} // your webview  source
 ref={webviewRef}
 injectedJavaScript={runFirst}  // pass data to web from react native
/>

 /* In your webview now you can access using  */
<script>
  document.addEventListener("message", function(data) {
                       alert(data.data)
 });
</script>
Collapse
 
prajyotdukse profile image
prajyotdukse

Hi @mukesh,

How do I pass dynamic values from react native to web view.
Static values I am able to pass but struggling to pass dynamic token

Regards,
Prajyot

Thread Thread
 
mukeshmandiwal profile image
Mukesh Mandiwal

JSON.stringify your dynmaic token and add to injectedJavaScript = {json.stringfy(yourtoekn)}