Márcio Fornari
Márcio Fornari

Reputation: 33

Getting and Passing variables inside React Native from Webview

i'm using [react-native-webview][1] in my project React Native. My webview has a javascript array, i need get this Array and show the values inside one menu, like this Slide Menu: https://raw.githubusercontent.com/instea/react-native-popup-menu/master/android.demo.gif

Code:

function WebViewPage(){
    const html = `
           <html>
           <body>
            <div id="reportContainer">here apear the content..</div>
            <script>
                  var reportContainer = document.getElementById('reportContainer');
                   var pages = [];
              reportContainer.getPages().then(function (reportPages) {
              //HERE RETURN A LIST FROM PAGES FROM MY REPORT..
              pages = reportPages;
              });
          </script>
          </body> 
           </html>
    `
   return(
    <Page>
     <WebView source={{html:html}} />
   </Page>
  );
}

export default WebViewPage;

Basically i need get the pages array and put on Menu at my Header. I was thinking work with hooks, but i don't know how to get this array, any ideas? Thank you. [1]: https://github.com/react-native-community/react-native-webview

Upvotes: 3

Views: 5940

Answers (1)

Chanuka Sandeepa
Chanuka Sandeepa

Reputation: 720

You can use onMessage callback function on webview component.

function WebViewPage(){
    const html = `
           <html>
           <body>
           <div id="reportContainer">here apear the content..</div>
           <script>
              var reportContainer = document.getElementById('reportContainer');
              var pages = [];
              reportContainer.getPages().then(function (reportPages) {
                 //HERE RETURN A LIST FROM PAGES FROM MY REPORT..
                 pages = reportPages;
                 window.postMessage(pages);
              });
           </script>
           </body> 
           </html>
    `
   const onMessage(data) { 
      console.log(data);
   }

   return(
    <Page>
     <WebView onMessage={onMessage} source={{html:html}} />
   </Page>
  );
}

export default WebViewPage;

Upvotes: 2

Related Questions