方舟web使用及数据双向通信

一、需解决的问题:

  1. 怎么加载本地html文件;
  2. 加载成功后应用端怎么调用js中的方法;
  3. js中怎么将数据传给应用端、或js端怎么调用应用端的数据。 参考地址:

二、怎么加载本地html文件

typescript 复制代码
import { webview } from "@kit.ArkWeb";

@Component
export struct MyPage {
  controller: webview.WebviewController = new webview.WebviewController();
  
  build() {
    Column() {
      Web({ src: $rawfile("map/index.html"), controller: this.controller })
        .onPageEnd(() => {
          // 推荐在此loadUrl、设置自定义用户代理、注入JS对象等
          this.controller.runJavaScript("setLatLonCenterNoMark(112.12853720100244,32.014796804669224,'8')");
          this.controller.runJavaScript("addYhdMark('YHD',112.12853720100244,32.014796804669224,'测试名称','#00ff00')");
        })
    }
  }
}

三、加载成功后应用端怎么调用js中的方法

可通过:

kotlin 复制代码
  this.controller.runJavaScript("")

直接引用js中的方法。

四、js中怎么将数据传给应用端、或js端怎么调用应用端的数据

有两种方法,我理解的分为:注册型与端口监听型,下面说说这两种方法的具体实现

1、注册型

应用侧代码:

scala 复制代码
import { webview } from "@kit.ArkWeb";
import { hilog } from "@kit.PerformanceAnalysisKit";

class TestClass {
  constructor() {
  }

  test(name:string): string {
    hilog.info(0,"测试",name)
    return 'ArkTS Hello World!';
  }
}
@Component
export struct MyPage {
  controller: webview.WebviewController = new webview.WebviewController();
  // 声明需要注册的对象
  @State testObj: TestClass = new TestClass();

  build() {
    Column() {
      Web({ src: $rawfile("map/index.html"), controller: this.controller })
        .onPageEnd(() => {
          // 推荐在此loadUrl、设置自定义用户代理、注入JS对象等
          this.controller.runJavaScript("setLatLonCenterNoMark(112.12853720100244,32.014796804669224,'8')");
          this.controller.runJavaScript("addYhdMark('YHD',112.12853720100244,32.014796804669224,'测试名称','#00ff00')");
        })
          // 将对象注入到web端
        .javaScriptProxy({
          object: this.testObj,
          name: "testObjName",
          methodList: ["test"],
          controller: this.controller,
          // 可选参数
          asyncMethodList: [],
          permission: '{"javascriptProxyPermission":{"urlPermissionList":[{"scheme":"resource","host":"rawfile","port":"","path":""},' +
            '{"scheme":"e","host":"f","port":"g","path":"h"}],"methodList":[{"methodName":"test","urlPermissionList":' +
            '[{"scheme":"https","host":"xxx.com","port":"","path":""},{"scheme":"resource","host":"rawfile","port":"","path":""}]},' +
            '{"methodName":"test11","urlPermissionList":[{"scheme":"q","host":"r","port":"","path":"t"},' +
            '{"scheme":"u","host":"v","port":"","path":""}]}]}}'
        })
    }
  }
}

js端调用应用端方法

2、监听型

主要是通过创建2个port,一个放在应用端使用,一个放在js端使用来达到互相通信

应用侧代码

typescript 复制代码
import { BusinessError } from '@kit.BasicServicesKit';
import { hilog } from '@kit.PerformanceAnalysisKit';
import { webview } from '@kit.ArkWeb';

@Component
export struct TxlPage {
  controller: webview.WebviewController = new webview.WebviewController();
  //第二种方法
  ports: webview.WebMessagePort[] = [];
  @State receivedFromHtml: string = 'Display received message send from HTML';
  @State sendFromEts: string = 'Send this message from ets to HTML';

  build() {
    Column() {
      Web({ src: $rawfile("map/index.html"), controller: this.controller })
        .onPageEnd(() => {
         // 推荐在此loadUrl、设置自定义用户代理、注入JS对象等
        this.controller.runJavaScript("setLatLonCenterNoMark(112.12853720100244,32.014796804669224,'8')");
        this.controller.runJavaScript("addYhdMark('YHD',112.12853720100244,32.014796804669224,'测试名称','#00ff00')");

          try {
            // 1、创建两个消息端口。
            this.ports = this.controller.createWebMessagePorts();
            if (this.ports && this.ports[0] && this.ports[1]) {
              // 2、在应用侧的消息端口(如端口1)上注册回调事件。
              this.ports[1].onMessageEvent((result: webview.WebMessage) => {
                let msg = 'Got msg from HTML:';
                if (typeof (result) === 'string') {
                  hilog.warn(0,'测试',`received string message from html5, string is: ${result}`);
                  msg = msg + result;
                } else if (typeof (result) === 'object') {
                  if (result instanceof ArrayBuffer) {
                    hilog.warn(0,'测试1',`received arraybuffer from html5, length is: ${result.byteLength}`);
                    msg = msg + 'length is ' + result.byteLength;
                  } else {
                    hilog.info(1,"",'not support');
                  }
                } else {
                  hilog.info(1,"",'not support');
                }
                this.receivedFromHtml = msg;
              })
              // 3、将另一个消息端口(如端口0)发送到HTML侧,由HTML侧保存并使用。
              this.controller.postMessage('__init_port__', [this.ports[0]], '*');
            } else {
              console.error(`ports is null, Please initialize first`);
            }
          } catch (error) {
            hilog.info(1,"",'初始化出错');
            console.error(`ErrorCode: ${(error as BusinessError).code},  Message: ${(error as BusinessError).message}`);
          }
      })
    }
  }
}

js端

csharp 复制代码
//监听应用端发送过来的消息
var h5Port;
window.addEventListener('message', function (event) {
    if (event.data === '__init_port__') {
        if (event.ports[0] !== null) {
            h5Port = event.ports[0]; // 1. 保存从应用侧发送过来的端口。
            h5Port.onmessage = function (event) {
                // 2. 接收ets侧发送过来的消息。
                var msg = 'Got message from ets:';
                var result = event.data;
                if (typeof(result) === 'string') {
                    clearFeaturesByLayerName("select_point_name");
                    alert('received string message from html5, string is: ${result}');
                    msg = msg + result;
                } else if (typeof(result) === 'object') {
                    if (result instanceof ArrayBuffer) {
                        alert('received arraybuffer from html5, length is: ${result.byteLength}');
                        msg = msg + 'length is ' + result.byteLength;
                    } else {
                        alert('not support');
                    }
                } else {
                    alert('not support');
                }
            }
        }
    }
})

回传给应用端

觉得写得好麻烦点赞鼓励下,谢谢

相关推荐
yuanlaile4 小时前
Flutter开发HarmonyOS鸿蒙App商业项目实战已出炉
flutter·华为·harmonyos
cooldream20094 小时前
【案例实战】智能出行导航助手HarmonyOS 开发全流程复盘
华为·harmonyos
CodeCaptain4 小时前
可直接落地的「Flutter 桥接鸿蒙 WebSocket」端到端实施方案
websocket·flutter·harmonyos
猫林老师4 小时前
HarmonyOS图形图像处理与OpenGL ES实战
harmonyos
白鹿第一帅4 小时前
【成长纪实】星光不负 码向未来|我的 HarmonyOS 学习之路与社区成长故事
harmonyos·白鹿第一帅·成都ug社区·csdn成都站·鸿蒙开放能力·鸿蒙学习之路·鸿蒙第一课
俩毛豆5 小时前
【页面路由导航】三步实现页面跳转的完整示例
前端·harmonyos
羑悻的小杀马特6 小时前
探秘仓颉:当函数式编程遇见面向对象王国,当协程风暴席卷并发荒原——从基础语法到实战测试联动的多维编程奇遇记
华为·harmonyos·仓颉·仓颉征文·个人感受·标准库源码·语法剖析
LucianaiB7 小时前
【案例实战】基于分布式能力的跨设备任务协同应用开发
harmonyos·鸿蒙·1024程序员节·案例实战
摘星编程20 小时前
【成长纪实】HarmonyOS Next学习地图:新手避坑指南与核心知识点拆解
学习·华为·harmonyos·鸿蒙开发
爱笑的眼睛111 天前
HarmonyOS生物识别认证深度解析:从指纹到人脸的安全实践
华为·harmonyos