前端页面和原生页面如何进行通信?

前端页面和原生页面如何进行通信?

HarmonyOS
2024-08-06 18:57:05
浏览
收藏 0
回答 1
待解决
回答 1
按赞同
/
按时间
橱柜里的蛙

html

<!--xxx.html-->
<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>WebView Message Port Demo</title>
</head>
<body>
<h1>WebView Message Port Demo</h1>
<div>
    <input type="button" value="SendToEts" onclick="PostMsgToEts(msgFromJS.value);"/><br/>
    <input id="msgFromJS" type="text" value="send this message from HTML to ets"/><br/>
</div>
<p class="output">display received message send from ets</p>
</body>
<script>
    var h5Port;
    var output = document.querySelector('.output');
    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') {
                    console.info(`received string message from html5, string is: ${result}`);
                    msg = msg + result;
                  } else if (typeof(result) === 'object') {
                    if (result instanceof ArrayBuffer) {
                      console.info(`received arraybuffer from html5, length is: ${result.byteLength}`);
                      msg = msg + 'lenght is ' + result.byteLength;
                    } else {
                      console.info('not support');
                    }
                  } else {
                    console.info('not support');
                  }
                  output.innerHTML = msg;
                }
            }
        }
    })

    // 3. 使用h5Port向应用侧发送消息。
    function PostMsgToEts(data) {
        if (h5Port) {
          h5Port.postMessage(data);
        } else {
          console.error('h5Port is null, Please initialize first');
        }
    }
</script>
</html>

arkTS:

import web_webview from '@ohos.web.webview';
import business_error from '@ohos.base';
@Entry
@Component
struct Index {
  controller: web_webview.WebviewController = new web_webview.WebviewController();
  ports: web_webview.WebMessagePort[] = [];
  @State sendFromEts: string = 'Send this message from ets to HTML';
  @State receivedFromHtml: string = 'Display received message send from HTML';
  build() {
    Column() {
      // 展示接收到的来自HTML的内容
      Text(this.receivedFromHtml)
      // 输入框的内容发送到HTML
      TextInput({placeholder: 'Send this message from ets to HTML'})
        .onChange((value: string) => {
          this.sendFromEts = value;
        })

      // 该内容可以放在onPageEnd生命周期中调用。
      Button('postMessage')
        .onClick(() => {
          try {
            // 1、创建两个消息端口。
            this.ports = this.controller.createWebMessagePorts();
            // 2、在应用侧的消息端口(如端口1)上注册回调事件。
            this.ports[1].onMessageEvent((result: web_webview.WebMessage) => {
              let msg = 'Got msg from HTML:';
              if (typeof(result) === 'string') {
                console.info(`received string message from html5, string is: ${result}`);
                msg = msg + result;
              } else if (typeof(result) === 'object') {
                if (result instanceof ArrayBuffer) {
                  console.info(`received arraybuffer from html5, length is: ${result.byteLength}`);
                  msg = msg + 'lenght is ' + result.byteLength;
                } else {
                  console.info('not support');
                }
              } else {
                console.info('not support');
              }
              this.receivedFromHtml = msg;
            })
            // 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}`);
          }
        })

      // 4、使用应用侧的端口给另一个已经发送到html的端口发送消息。
      Button('SendDataToHTML')
        .onClick(() => {
          try {
            if (this.ports && this.ports[1]) {
              this.ports[1].postMessageEvent(this.sendFromEts);
            } else {
              console.error(`ports is null, Please initialize first`);
            }
          } catch (error) {
            let e: business_error.BusinessError = error as business_error.BusinessError;
            console.error(`ErrorCode: ${e.code},  Message: ${e.message}`);
          }
        })
      Web({ src: $rawfile('test.html'), controller: this.controller })
    }
    .width('100%')
    .height('100%')
    .justifyContent(FlexAlign.Center)
  }
}

class testClass {
  constructor() {
  }
  test(): string {
    return 'ArkTS Hello World!';
  }
}
分享
微博
QQ
微信
回复
2024-08-06 20:30:22
相关问题
原生页面webview如何进行参数传递
514浏览 • 1回复 待解决
如何进行页面横竖屏切换
1940浏览 • 1回复 待解决
页面横竖屏如何进行切换
392浏览 • 1回复 待解决
ArkTS如何进行页面间传值?
1118浏览 • 1回复 待解决
HarmonyOS HAP之间如何进行通信
375浏览 • 1回复 待解决
HarmonyOS如何进行跨module的页面跳转
396浏览 • 1回复 待解决
Web组件h5页面如何交互?
163浏览 • 1回复 待解决
HarmonyOS 页面如何设置全屏显示?
296浏览 • 1回复 待解决
PolarDB 如何进行数据通信
2912浏览 • 1回复 待解决
如何使用DevTools工具调试前端页面
423浏览 • 1回复 待解决
HarmonyOS WebView组件前端页面调试
171浏览 • 1回复 待解决
page页面如何设置为横屏显示
1641浏览 • 1回复 待解决
H5页面如何与ArkTS交互
2962浏览 • 1回复 待解决