HarmonyOS H5调用原生扫码功能?

如题:HarmonyOS H5调用原生扫码功能?

阅读 417
1 个回答

请参考demo:

// PageWeb.ets
import web_webview from '@ohos.web.webview'
import { scanCore, scanBarcode } from '@kit.ScanKit';
// 导入默认界面需要的日志模块和错误码模块
import { hilog } from '@kit.PerformanceAnalysisKit';
import { BusinessError } from '@kit.BasicServicesKit';
let options: scanBarcode.ScanOptions = {
  scanTypes: [scanCore.ScanType.ALL],
  enableMultiMode: true,
  enableAlbum: true };
class TestClass {
  async scan(): Promise<string> {
    let scanResult: string = ''
    const result: scanBarcode.ScanResult = await scanBarcode.startScanForResult(getContext(this), options);
    // 收到扫码结果后返回
    scanResult = result.originalValue; hilog.info(0x0001, '[Scan CPSample]', 'Promise scan result: %{public}s', JSON.stringify(result));
    return scanResult; }
}
@Entry
@Component
export struct PageWeb {
  readonly webUrl: string | Resource = 'www.huawei.com'
  readonly controller: WebviewController = new web_webview.WebviewController()
  userAgentAlreadySet: boolean = false
  @State customUserAgent?: string = undefined
  @State testObj: TestClass = new TestClass();
  build() {
    if (this.customUserAgent) {
      Column() {
        Web({ src: $rawfile('scan.html'), controller: this.controller }) .domStorageAccess(true) .javaScriptProxy({
          object: this.testObj,
          name: "testObjName",
          methodList: ["scan"],
          controller: this.controller })
      }
    }
  }
  aboutToAppear(): void {
    // 模拟异步构建 customUserAgent 过程
    setTimeout(() => this.customUserAgent = 'ua/value', 200)
  }
  applyCustomUserAgent(): void {
    this.userAgentAlreadySet = true
    let defaultUserAgent = this.controller.getUserAgent()
    this.controller.setCustomUserAgent(defaultUserAgent + ' ' + this.customUserAgent)
    this.controller.loadUrl(this.webUrl) }
  onBackPress(): boolean | void {
  }
}

scan.html代码(放在rawfile目录下):

<!-- index.html -->
  <!DOCTYPE html>
  <html>
  <body>
  <button type="button" onclick="callArkTS()">Click Me!</button>
  <p id="demo"></p>
  <script>
  async function callArkTS() {
    let str = await testObjName.scan();
    document.getElementById("demo").innerHTML = str;
    console.info('ArkTS Hello World! :' + str);
  }
  </script>
  </body>
  </html>
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
logo
HarmonyOS
子站问答
访问
宣传栏