2

以下是 Web 视图,我使用的是内联 HTML。

<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;
              }
            }
          }
        }}
      />

在下面找到内联的相同 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> -->

当我点击扫描按钮onMessage被调用并且正在传递的数据被正确接收。我将根据收到的数据调用不同的函数。

以下是相机调用的函数,

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函数处理回调一个 javascript 方法,或者它只会填充一个文本框,具体取决于data.operation.type. 所以现在被data.operation.type调用了,但我无法调用作为对象输入接收的函数。对象如下,CALLBACKperformCallback

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

fillQRCode是存在于<script>html 标记中的函数。

如何将接收到的函数(接收时为字符串形式)转换为函数和调用相同的函数。

4

1 回答 1

0

我修改了传递函数的方式,如下所示,

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

即,我没有传递整个函数(我现在觉得这是错误的方法),我只传递了函数名并按如下方式调用了函数,

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);
    }
  `);
  };
于 2020-01-17T06:16:18.717 回答