鸿蒙与原生WebH5的通信-DsBridge

OpenHarmony三方库中心仓   DsBridge第三方库

DsBridge是鸿蒙与原生WebH5的通信的一个三方库,上述的openharmony中心仓已经有具体的方法以及如何使用,话不多说,下面是关于DsBridge使用的使用示例,可直接粘贴代码查看日志:

harmony代码

import { JavaScriptInterface, WebViewControllerProxy } from '@hzw/ohos-dsbridge';

interface People {
  name: string
  age: number
}

@Entry
@Component
struct DsBridgePage {
  private controller: WebViewControllerProxy = WebViewControllerProxy.createController()
  private localPath = $rawfile('index.html')
  @State isLoading: boolean = true
  @State peopleInfo: People = {
    name: '张三',
    age: 18
  }

  aboutToAppear() {
    this.controller.addJavascriptObject(this)
    this.controller.setClosePageListener(() => {
      return true; // false 会拦截关闭页面
    })
  }

  aboutToDisappear() {
    this.controller.destroy()
  }

  // 使用注册形式的方法给web页面调用,同时将参数传给web页面
  registerShowHarmonyInfo() {
    this.controller.callJs('showAlert', [this.peopleInfo], (result: boolean) => {
      console.log('resultInfo-ShowAlert', result);
    })
  }

  @JavaScriptInterface(false)
  test(args: string): string {
    console.log('来自WebH5的参数', args);
    // return是从鸿蒙端传给WebH5的参数
    return ` ${JSON.stringify(this.peopleInfo)}`
  }

  build() {
    Column() {
      Web({ src: this.localPath, controller: this.controller.getWebViewController() })
        .javaScriptAccess(true)
        .javaScriptProxy(this.controller.javaScriptProxy)
        .onAlert((event) => {
          return false
        })
        .onPageEnd(() => {
          // 需要在页面加载end之后调用
          this.registerShowHarmonyInfo()
        })
        .onProgressChange((event) => {
          if (event?.newProgress == 100) {
            this.isLoading = false
          }
        })
        .onConsole((event) => {
          console.info('getMessage:' + event?.message.getMessage());
          return false;
        })
        .width('100%')
        .height('100%')
        .backgroundColor("#ffeef5ee")

    }
    .height('100%')
    .width('100%')
  }
}

H5代码

<!doctype html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport"
        content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title></title>
    <script src="https://cdn.jsdelivr.net/npm/dsbridge/dist/dsbridge.js"> </script>
    <style type="text/css">
        html,
        body {
            width: 100%;
            height: 100%;
            margin: 0;
        }

        h1,
        p,
        ul,
        ol {
            margin: 0;
            padding: 0;
        }

        .wrapper {
            height: 100%;
            padding: 0 7px;
            overflow: scroll;
            padding: 50px 0 0 0;
        }

        .call-native {
            margin: 6px;
            width: calc(100% - 12px);
            height: 40px;
        }

        .msg-wrapper {
            position: fixed;
            left: 0;
            top: 0;
        }

        .msg {
            margin: 10px;
            color: red
        }
    </style>

</head>

<body>
    <div class="msg-wrapper">
        <p class="msg"></p>
    </div>
    <div class="wrapper">
        <button class="call-native" onclick="callNative1()">检测原生test()方法</button>
        <button class="call-native" onclick="callNative2()">点击调用test()方法</button>
    </div>
</body>
<script>
    // 检测是否存在test()方法
    const callNative1 = () => {
        let have = dsBridge.hasNativeMethod("test")
        updateMsg("test方法 " + have)
    }
    // 点击调用test()方法
    const callNative2 = () => {
        // 推荐使用字符串传给纯血鸿蒙,鸿蒙可以直接接收到参数
        let msg = dsBridge.call('test', JSON.stringify({ name: 'maomao', age: 18 }))
        console.log("来自Harmony端传入的参数", msg);
        updateMsg(msg)
    }

    // 直接调用test2()方法
    const callNative3 = () => {
        let msg = dsBridge.call('test', JSON.stringify({ name: 'maomao', age: 18 }))
        console.log("来自Harmony端传入的参数", msg);
        updateMsg(msg)
    }

    callNative3()

    // 注册的形式调用鸿蒙端的方法并接收参数
    const register1 = () => {
        dsBridge.register('showAlert', (msg) => {
            // msg是鸿蒙端传递过来的参数
            console.log("showAlertmsg", JSON.stringify(msg));
            // return返回值,鸿蒙中可以使用箭头函数接收到
            return false
        })
    }
    
    register1()

    function updateMsg(msg) {
        let msgEle = document.querySelector(".msg")
        msgEle.innerHTML = msg
    }
</script>

</html>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值