Search code examples
react-nativereact-native-webview

react-native-webview Calling a specific javascript function from the html


Following is the web view, I am using inline HTML for the same.

<WebView
        javaScriptEnabled={true}
        domStorageEnabled={true}
        allowFileAccess={true}
        originWhitelist={['*']}
        style={{height: deviceHeight, width: deviceWidth, margin: 10}}
        // source={{ uri: 'https://www.google.com/'}}
        source={{
          html:
            '<script> function invokeHello() { window.ReactNativeWebView.postMessage("Hello") } function fillQRCode() { window.alert("filling qrcode"); document.getElementById("qr_code").value = "QR Code"; } function scanQRCode() { let data = {"nativeItemToAccess": "camera", "operation": { "type": "CALLBACK", "fieldId": "qr_code", "callback": `${fillQRCode}` }}; window.ReactNativeWebView.postMessage(JSON.stringify(data)); }</script> <!-- <form method="get" enctype="application/x-www-form-urlencoded" action="/html/codes/html_form_handler.cfm" onSubmit="invokeHello()"> --> <p><label>Name<input type="text" name="customer_name" required></label> </p> <p><label>Phone <input type="tel" name="phone_number" id="phone_number"></label></p> <p><label>QR Code <input type="text" disabled name="qr_code" id="qr_code"></label><p></p><button onclick="scanQRCode()">Scan</button></p></p> <p><button>Submit Booking</button></p><!-- </form> -->',
        }}
        // injectedJavaScript={runFirst}
        ref={r => (this.webref = r)}
        onMessage={event => {
          if (this.webref) {
            let data = JSON.parse(event.nativeEvent.data);
            console.log('1: data being received: ', data);
            if(data) {
              switch(data.nativeItemToAccess) {
                case 'camera':
                  this.performOperation(data);
                  break;
                case 'test':
                  alert('test is invoked');
                  break;
              }
            }
          }
        }}
      />

Find below the same html which is inline (posting just to make it more readable),

<script> 
  function invokeHello() { window.ReactNativeWebView.postMessage("Hello") }
  function fillQRCode() { window.alert("filling qrcode"); document.getElementById("qr_code").value = "QR Code"; }
  function scanQRCode() {

    let data = {"nativeItemToAccess": "camera", "operation": {
      "type": "CALLBACK",
      "fieldId": "qr_code",
      "callback": `${fillQRCode}`
    }};
    window.ReactNativeWebView.postMessage(JSON.stringify(data));
  }
</script> 
<!-- <form method="get" enctype="application/x-www-form-urlencoded" action="/html/codes/html_form_handler.cfm" onSubmit="invokeHello()"> -->
   <p><label>Name<input type="text" name="customer_name" required></label> </p>
   <p><label>Phone <input type="tel" name="phone_number" id="phone_number"></label></p>
   <p><label>QR Code <input type="text" disabled name="qr_code" id="qr_code"></label><p></p><button onclick="scanQRCode()">Scan</button></p></p>
   <p><button>Submit Booking</button></p>
<!-- </form> -->

When I click on scan button onMessage gets invoked and the data which is being passed is received correctly. I will be calling different functions depending on the data received.

Below are the functions which are called for camera,

performOperation = data => {
    switch (data.operation.type) {
      case 'FIELD_UPDATE':
        this.updateField(data.operation.fieldId);
        break;
      case 'CALLBACK':
        this.performCallback(data.operation.callback);
        break;
    }
  };

  performCallback = callback => {
    console.log('2: callback: ', callback);
    this.webref.injectJavaScript(`
    try {
      var fn = window[${callback}];
      if (typeof fn === "function") {
        fn();
      } else {
        window.alert('this is not a function '+ typeof fn);
      }
      true;
    } catch (e) {
      window.alert('unable to call the function: '+ e);
    }
  `);
  };

  updateField = fieldId => {
    this.webref.injectJavaScript(`
    document.getElementById("${fieldId}").value = "QR Code";
    `);
  };

performOperation function handles calling back a javascript method or it will just fill a text box, depending on the data.operation.type. So now the data.operation.type is CALLBACK so performCallback gets called, but I am unable to call the function which is received as input in the object. The object is as follows,

{"nativeItemToAccess": "camera", "operation": {
"type": "CALLBACK",
"fieldId": "qr_code",
"callback": ${fillQRCode}
}};

fillQRCode is the function present in the <script> tag of the html.

How do I convert the received function, which is in the form of string when received, to function and call the same.


Solution

  • I modified the way I am passing the function as follows,

    {"nativeItemToAccess": "camera", "operation": {
          "type": "CALLBACK",
          "fieldId": "qr_code",
          "callback": "fillQRCode"
        }};
    

    i.e instead of passing the whole function (which was wrong approach I feel now) I passed just the function name and called the function as follows,

    performCallback = callback => {
        console.log('2: callback: ', callback);
        var qrCode = 'zdjkcnsjkdnsdkfjnjk';
        this.webref.injectJavaScript(`
        try {
          ${callback}("${qrCode}")
          true;
        } catch (e) {
          window.alert('unable to call the function: '+ e);
        }
      `);
      };