HarmonyOS 前端调用原生,原生调用前端的方法?

前端先调用原生,原生处理好结果,然后将数据上传到前端(先后顺序问题)

其他系统端实现的方式:

public void H5CallLiveSurvivalAuth(String param) {
  // ToastUtils.show("H5CallLiveSurvivalAuth");
  Gson gson = new Gson();
  HumanFaceParams humanFaceParams = gson.fromJson(param, HumanFaceParams.class);
  AliFace.getInstance().launch(WebViewActivity.this, humanFaceParams.getCertifyId(), new ICallback() {
    @Override
    public void onResponse(Map<String, String> response) {
      // 不管成功失败,都回调
      runOnUiThread(() -> {
        String responseStr = JSON.toJSONString(response);
        webView.loadUrl("javascript:NativeCallLiveSurvivalAuth('" + responseStr + "')");
      });
    }
  });
}

前端调用原生的方法,原生拉着人脸,然后将返回的结果上传到前端

HarmonyOS实现的方法

/**
 * @param param
 */
async H5CallLiveSurvivalAuth(param:string): Promise<string> {
  // ToastUtil.showToast("H5调用人脸");
  let data=JSONUtils.json2Bean(HumanFaceParams,param);
  let certifyId=data?.certifyId;
  let faceResult: MPFaceResult = await MPFace.startVerify(certifyId);
  let toast = '';
  if (faceResult.isSuccess()) {
  //客户端认证通过,去服务端查询最终结果
  toast = faceResult.msg;
}
else {
  //认证失败
  toast = JSON.stringify(faceResult);
}
SpConstants.TOAST=toast;
return toast;
}

但是如何再次调用方法将返回的结果toast信息上传到前端呢?这个先后顺序如何控制?

阅读 499
1 个回答

参考此api即可

https://developer.huawei.com/consumer/cn/doc/harmonyos-references-V5/ts-basic-components-web-V5\#javascriptproxy

import webview from '@ohos.web.webview';

class WebObj {
  controller: WebviewController;
  constructor(controller: WebviewController) {
    this.controller = controller;
  }

  webString(): void {
    this.controller.runJavaScript("callback(true)");
  }

}

@Entry
@Component
struct Index {
  @State webTestObj: WebObj = new WebObj(new webview.WebviewController());

  build() {
    Column() {
      Web({
        src: $rawfile('index.html'),
        controller: this.webTestObj.controller
      })
        .onControllerAttached(()=>{
          this.webTestObj.controller.registerJavaScriptProxy(this.webTestObj, "objTestName", ["webString"]);
          this.webTestObj.controller.refresh();
        })
    }
  }
}
<!Document>
<html>
<head>
    <title>测试</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<style>
    html,
    body {
      margin: 0px;
      padding: 0px;
    }
    button {
      width: 100%;
      height: 50px;
    }
</style>
<body>
<div>
    <div>
        <div>test.html</div>
        <button id="echo">人脸识别</button>
    </div>
</div>
<script>

    document.querySelector('#echo').addEventListener('click', async () => {
      objTestName.webString({'event':'调用人脸识别'})
    })
    function callback(type){
      document.write(type)
    }
</script>
</body>
</html>
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进