HarmonyOS H5调用原生扫码功能

HarmonyOS
3天前
浏览
收藏 0
回答 1
待解决
回答 1
按赞同
/
按时间
Heiang

请参考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>
分享
微博
QQ
微信
回复
3天前
相关问题
HarmonyOS h5拉起系统页面的demo
285浏览 • 1回复 待解决
HarmonyOS H5原生交互
31浏览 • 1回复 待解决
HarmonyOS web原生H5如何交互?
562浏览 • 1回复 待解决
HarmonyOS H5如何复用?
206浏览 • 1回复 待解决
HarmonyOS h5原生交互、页面状态机
72浏览 • 1回复 待解决
H5原生调JSbrige的demo示例
251浏览 • 1回复 待解决
HarmonyOS H5打开原生相机
34浏览 • 1回复 待解决
HarmonyOS 原生H5页面交互
40浏览 • 1回复 待解决
HarmonyOS webview内嵌H5功能异常
74浏览 • 1回复 待解决
HarmonyOS 应用涉及H5,如何使用?
256浏览 • 1回复 待解决
HarmonyOS 原生怎么主动触发消息给h5
86浏览 • 1回复 待解决
HarmonyOS H5调用APP图库选择图片
29浏览 • 1回复 待解决
HarmonyOS 是否有功能
85浏览 • 1回复 待解决
Web能直接加载h5吗?
3091浏览 • 2回复 待解决
HarmonyOS h5加载二维屏幕变亮
36浏览 • 1回复 待解决
跨平台开发,h5怎么调试?
263浏览 • 1回复 待解决