需要web组件JSBridge通信的demo

需要web组件JSBridge通信的demo。

HarmonyOS
2024-11-05 11:01:34
1788浏览
收藏 0
回答 1
回答 1
按赞同
/
按时间
Heiang

示例代码:

// index.ets页面 
import web_webview from '@ohos.web.webview'; 
import business_error from '@ohos.base'; 
class H5Object{ 
  'name':string 
  'age':string 
  'sex':string 
} 
@Entry 
@Component 
struct Index { 
  controller:web_webview.WebviewController = new web_webview.WebviewController(); 
  scroller: Scroller = new Scroller() 
  ports:web_webview.WebMessagePort[] = []; 
  @State message: string = '应用侧'; 
  @State receivedFromHtml:string = ''; 
  @State receivedObjectFromHtml:H5Object = { 
    name:'Helen', 
    age:'20', 
    sex:'Girl' 
  }; 
  @State receivedArrayFromHtml:Array<string> = ['我是第一条数据','我是第二条数据','我是第三条数据']; 
  @State receivedArrayObjectFromHtml:H5Object[] = [ 
    { 
      name:'Helen', 
      age:'20', 
      sex:'Girl' 
    }, 
    { 
      name:'Alice', 
      age:'19', 
      sex:'Girl' 
    }, 
    { 
      name:'Wendy', 
      age:'18', 
      sex:'Girl' 
    }, 
  ]; 
  aboutToAppear() { 
    // 配置Web开启调试模式 
    web_webview.WebviewController.setWebDebuggingAccess(true); 
  } 
  onPageShow() { 
    setTimeout(()=>{ 
      this.getDataFromH5(); 
    },500) 
  } 
  getDataFromH5() { 
    let tag = '[TAG-LCF]'; 
    try{ 
      // 1、创建两个消息端口 
      this.ports = this.controller.createWebMessagePorts(); 
      // 2、在应用侧的消息端口(端口1)上注册回调事件。 
      this.ports[1].onMessageEvent((result:web_webview.WebMessage)=>{ 
        // 判断数据类型是否是对象 
        let isObject = false; 
        // 判断数据类型是否是数组 
        let isArray = false; 
        let arr = []; 
        // 如果数据是字符串、数字走catch,只有数组、对象、数组对象类型的数据走try 
        try{ 
          arr = JSON.parse(result as string); 
          isObject = true; 
          if(Array.isArray(arr)){ 
            isArray = true; 
          }else{ 
            isArray = false; 
          } 
        } 
        catch(error){ 
          let e: business_error.BusinessError = error as business_error.BusinessError; 
          console.error(`ErrorCode: ${e.code},  Message: ${e.message}`); 
        } 
        if(typeof(result) === 'string' && !isObject){ 
          // H5侧传过来的是字符串数据 
          this.receivedFromHtml = result; 
          return this.receivedFromHtml; 
        }else if(typeof(result) === 'string' && isObject && !isArray){ 
          // H5侧传过来的是对象数据 
          this.receivedObjectFromHtml = JSON.parse(result) as H5Object; 
          return this.receivedObjectFromHtml; 
        }else if(typeof(result) === 'string' && isObject && isArray){ 
          // H5侧传过来的是数组对象数据 
          if (JSON.parse(result)[0] !== '第一条数据'){ 
            this.receivedArrayObjectFromHtml = JSON.parse(result); 
            return this.receivedArrayObjectFromHtml 
          } 
          // H5侧传过来的是数组数据 
          this.receivedArrayFromHtml = JSON.parse(result); 
          return this.receivedArrayFromHtml; 
        } 
        // 必须return数据,否则报错 
        return this.receivedFromHtml; 
      }) 
      // 3、将另一个消息端口(端口0)发送到HTML侧,由HTML侧保存并使用 
      this.controller.postMessage('__init_port__',[this.ports[0]],'*'); 
    }catch(error){ 
      let e: business_error.BusinessError = error as business_error.BusinessError; 
      console.error(`ErrorCode: ${e.code},  Message: ${e.message}`); 
    } 
  } 
  // 异步数据的发送 
  async AsynData(){ 
    if (this.ports && this.ports[1]) { 
      await this.ports[1].postMessageEvent('倒计时3秒'); 
    } else { 
      console.error(`ports is null, Please initialize first`) 
    } 
  } 
  build() { 
    Column(){ 
      Scroll(this.scroller){ 
        Column() { 
          Text(this.message) 
            .fontSize(20) 
            .fontWeight(FontWeight.Bold) 
            .margin({ top: 10 }) 
          // 展示字符串 或 异步数据 
          Text('H5页面发送过来的String数据: ' + this.receivedFromHtml) 
            .margin({ top: 10, bottom: 10 }) 
          // 展示对象 
          Text('H5页面发送过来的Object数据: ') 
          Row({ space: 16 }) { 
            Text('姓名:' + this.receivedObjectFromHtml.name) 
            Text('性别:' + this.receivedObjectFromHtml.sex) 
            Text('年龄:' + this.receivedObjectFromHtml.age) 
          } 
          // 展示数组数据 
          Text('H5页面发送过来的Array数据:') 
          List() { 
            ForEach(this.receivedArrayFromHtml, (item: string) => { 
              ListItem() { 
                Text(item) 
              } 
            }) 
          } 
          .alignListItem(ListItemAlign.Center) 
          // 展示数组对象嵌套数据 
          List() { 
            ForEach(this.receivedArrayObjectFromHtml, (item: H5Object) => { 
              ListItem() { 
                Row() { 
                  Text('姓名:' + item.name) 
                  Text('性别:' + item.sex) 
                  Text('年龄:' + item.age) 
                } 
              } 
            }) 
          } 
          .alignListItem(ListItemAlign.Center) 
          Column() { 
            Button('发送String类型数据至H5侧') 
              .fontSize(12) 
              .margin({ bottom: 10 }) 
              .onClick(() => { 
                if (this.ports && this.ports[1]) { 
                  this.ports[1].postMessageEvent('来自应用侧String类型的数据'); 
                } else { 
                  console.error(`ports is null, Please initialize first`) 
                } 
              }) 
            Button('发送Object类型数据至H5侧') 
              .fontSize(12) 
              .margin({ bottom: 10 }) 
              .onClick(() => { 
                if (this.ports && this.ports[1]) { 
                  this.ports[1].postMessageEvent(JSON.stringify(this.receivedObjectFromHtml)); 
                } else { 
                  console.error(`ports is null, Please initialize first`) 
                } 
              }) 
            Button('发送Array类型数据至H5侧') 
              .fontSize(12) 
              .margin({ bottom: 10 }) 
              .onClick(() => { 
                if (this.ports && this.ports[1]) { 
                  this.ports[1].postMessageEvent(JSON.stringify(this.receivedArrayFromHtml)); 
                } else { 
                  console.error(`ports is null, Please initialize first`) 
                } 
              }) 
            Button('发送数组对象类型数据至H5侧') 
              .fontSize(12) 
              .margin({ bottom: 10 }) 
              .onClick(() => { 
                if (this.ports && this.ports[1]) { 
                  this.ports[1].postMessageEvent(JSON.stringify(this.receivedArrayObjectFromHtml)); 
                } else { 
                  console.error(`ports is null, Please initialize first`) 
                } 
              }) 
            Button('发送异步数据至H5侧') 
              .fontSize(12) 
              .margin({ bottom: 10 }) 
              .onClick(() => { 
                if (this.ports && this.ports[1]) { 
                  this.AsynData() 
                  setTimeout(()=>{ 
                    this.ports[1].postMessageEvent('来自应用侧的异步数据'); 
                  },3000) 
                } else { 
                  console.error(`ports is null, Please initialize first`) 
                } 
              }) 
          }.width('100%') 
        } 
      } 
      .height('50%') 
      .width('100%') 
      .scrollable(ScrollDirection.Vertical) 
      .backgroundColor('#FDE7E9') 
      Web({src:$rawfile('index.html'),controller:this.controller}) 
        .height('50%') 
        .onlineImageAccess(true) 
        .imageAccess(true) 
    } 
    .height('100%') 
    .width('100%') 
  } 
} 
// index.html代码,该文件放在rawfile文件夹下 
<!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>Document</title> 
  </head> 
  <body> 
  <h1>H5侧</h1> 
  <div> 
  <input type="button" value="发送String类型数
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.
  • 37.
  • 38.
  • 39.
  • 40.
  • 41.
  • 42.
  • 43.
  • 44.
  • 45.
  • 46.
  • 47.
  • 48.
  • 49.
  • 50.
  • 51.
  • 52.
  • 53.
  • 54.
  • 55.
  • 56.
  • 57.
  • 58.
  • 59.
  • 60.
  • 61.
  • 62.
  • 63.
  • 64.
  • 65.
  • 66.
  • 67.
  • 68.
  • 69.
  • 70.
  • 71.
  • 72.
  • 73.
  • 74.
  • 75.
  • 76.
  • 77.
  • 78.
  • 79.
  • 80.
  • 81.
  • 82.
  • 83.
  • 84.
  • 85.
  • 86.
  • 87.
  • 88.
  • 89.
  • 90.
  • 91.
  • 92.
  • 93.
  • 94.
  • 95.
  • 96.
  • 97.
  • 98.
  • 99.
  • 100.
  • 101.
  • 102.
  • 103.
  • 104.
  • 105.
  • 106.
  • 107.
  • 108.
  • 109.
  • 110.
  • 111.
  • 112.
  • 113.
  • 114.
  • 115.
  • 116.
  • 117.
  • 118.
  • 119.
  • 120.
  • 121.
  • 122.
  • 123.
  • 124.
  • 125.
  • 126.
  • 127.
  • 128.
  • 129.
  • 130.
  • 131.
  • 132.
  • 133.
  • 134.
  • 135.
  • 136.
  • 137.
  • 138.
  • 139.
  • 140.
  • 141.
  • 142.
  • 143.
  • 144.
  • 145.
  • 146.
  • 147.
  • 148.
  • 149.
  • 150.
  • 151.
  • 152.
  • 153.
  • 154.
  • 155.
  • 156.
  • 157.
  • 158.
  • 159.
  • 160.
  • 161.
  • 162.
  • 163.
  • 164.
  • 165.
  • 166.
  • 167.
  • 168.
  • 169.
  • 170.
  • 171.
  • 172.
  • 173.
  • 174.
  • 175.
  • 176.
  • 177.
  • 178.
  • 179.
  • 180.
  • 181.
  • 182.
  • 183.
  • 184.
  • 185.
  • 186.
  • 187.
  • 188.
  • 189.
  • 190.
  • 191.
  • 192.
  • 193.
  • 194.
  • 195.
  • 196.
  • 197.
  • 198.
  • 199.
  • 200.
  • 201.
  • 202.
  • 203.
  • 204.
  • 205.
  • 206.
  • 207.
  • 208.
  • 209.
  • 210.
  • 211.
  • 212.
  • 213.
  • 214.
  • 215.
  • 216.
  • 217.
  • 218.
  • 219.
  • 220.
  • 221.
  • 222.
  • 223.
  • 224.
  • 225.
  • 226.
  • 227.
  • 228.
  • 229.
  • 230.
  • 231.
  • 232.
  • 233.
  • 234.
  • 235.
分享
微博
QQ
微信
回复
2024-11-05 18:07:47


相关问题
HarmonyOS web组件jsbridge通信demo
317浏览 • 1回复 待解决
HarmonyOS web组件jsBridge通信
527浏览 • 1回复 待解决
需要提供c++到js通信demo
1040浏览 • 1回复 待解决
HarmonyOS jsbridge功能demo
323浏览 • 1回复 待解决
使用Web组件下载能力Demo
985浏览 • 1回复 待解决
需要视频录制、压缩demo
639浏览 • 1回复 待解决
HarmonyOS 官方web demo工程
477浏览 • 1回复 待解决
HarmonyOS 需要扫码demo
569浏览 • 1回复 待解决
HarmonyOS web和原生交互demo
352浏览 • 1回复 待解决
需要一个NFC读取demo
1192浏览 • 1回复 待解决
HarmonyOS 需要二级联动demo
715浏览 • 1回复 待解决
HarmonyOS组件通信机制
1147浏览 • 1回复 待解决
HarmonyOS web-view使用以及demo
556浏览 • 1回复 待解决
HarmonyOS JsBridge适配问题
463浏览 • 1回复 待解决
提问
该提问已有2人参与 ,帮助了8人