中国优质的IT技术网站
专业IT技术创作平台
IT职业在线教育平台
希望提供H5与应用侧数据交互的Demo,包含以下场景:
1:应用侧调用H5
2:H5调用应用侧
3:应用侧和H5数据通道连接
微信扫码分享
//场景1 //应用侧代码 import web_webview from '@ohos.web.webview'; import business_error from '@ohos.base'; /** * 应用侧调用h5 */ @Entry @Component struct ArkTSInvokeH5Page { controller: web_webview.WebviewController = new web_webview.WebviewController(); @State webResult: string = '' build() { Column() { Text(this.webResult).fontSize(20) Web({ src: $rawfile('ArkTSInvokeH5.html'), controller: this.controller }) .javaScriptAccess(true) .onPageEnd(e => { try { this.controller.runJavaScript( 'test()', (error, result) => { if (error) { let e: business_error.BusinessError = error as business_error.BusinessError; console.error(`run JavaScript error, ErrorCode: ${e.code}, Message: ${e.message}`); return; } if (result) { this.webResult = result console.info(`The test() return value is: ${result}`) } }); if (e) { console.info('url: ', e.url); } } catch (error) { let e: business_error.BusinessError = error as business_error.BusinessError; console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); } }) } } } //场景1 //html代码 <!-- index.html --> <!DOCTYPE html> <html> <meta charset="utf-8"> <body> Hello world! </body> <script type="text/javascript"> function test() { console.log('Ark WebComponent') return "This value is from index.html" } </script> </html> //场景2 //应用侧代码 import web_webview from '@ohos.web.webview'; /** *H5调用应用侧 */ class testClass { constructor() { } test(): string { return 'ArkTS Hello World!'; } } @Entry @Component struct H5InvokeArkTSPage { webviewController: web_webview.WebviewController = new web_webview.WebviewController(); // 声明需要注册的对象 @State testObj: testClass = new testClass(); build() { Column() { // web组件加载本地index.html页面 Web({ src: $rawfile('H5InvokeArkTS.html'), controller: this.webviewController}) // 将对象注入到web端 .javaScriptProxy({ object: this.testObj, name: "testObjName", methodList: ["test"], controller: this.webviewController }) }.height('100%').width('100%').justifyContent(FlexAlign.Center) } } //场景2 //html代码 <!DOCTYPE html> <html> <head> <style> #demo { text-align: center; font-size: 24px; /* 设置字体大小为24像素 */ } </style> </head> <body> <button type="button" onclick="callArkTS()">Click Me!</button> <p id="demo"></p> <script> function callArkTS() { let str = testObjName.test(); document.getElementById("demo").innerHTML = str; console.info('ArkTS Hello World! :' + str); } </script> </body> </html> //场景3 //应用侧代码 import web_webview from '@ohos.web.webview'; import business_error from '@ohos.base'; @Entry @Component struct ArkTSCommunicateWithH5Page { controller: web_webview.WebviewController = new web_webview.WebviewController(); ports: web_webview.WebMessagePort[] = []; @State sendFromEts: string = '发送到H5的数据:'; @State receivedFromHtml: string = '接收H5的信息:'; build() { Column() { // 展示接收到的来自HTML的内容 Text(this.receivedFromHtml) // 输入框的内容发送到HTML TextInput({placeholder: '发送消息到H5'}) .onChange((value: string) => { this.sendFromEts = value; }) Button('发送至H5') .onClick(() => { try { // 1、创建两个消息端口。 this.ports = this.controller.createWebMessagePorts(); // 2、在应用侧的消息端口(如端口1)上注册回调事件。 this.ports[1].onMessageEvent((result: web_webview.WebMessage) => { let msg = '来自H5:'; if (typeof(result) === 'string') { console.info(`接受至H5: ${result}`); msg = msg + result; } else if (typeof(result) === 'object') { if (result instanceof ArrayBuffer) { console.info(`接收h5: ${result.byteLength}`); msg = msg + 'lenght is ' + result.byteLength; } else { console.info('not support'); } } else { console.info('not support'); } this.receivedFromHtml = msg; }) 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}`); } try { if (this.ports && this.ports[1]) { this.ports[1].postMessageEvent(this.sendFromEts); } else { console.error(`ports 为空`); } } catch (error) { let e: business_error.BusinessError = error as business_error.BusinessError; console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); } }) Web({ src: $rawfile('ArkTSCommunicateWithH5Page.html'), controller: this.controller }) }.justifyContent(FlexAlign.Center) } } //场景3 //html代码 <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>H5和应用侧数据交互</title> </head> <body> <h1>H5和应用侧数据交互案例</h1> <div> <input type="button" value="Send" onclick="PostMsgToEts(msgFromJS.value);"/><br/> <input id="msgFromJS" type="text" value="请输入您要发送至ets的内容"/><br/> </div> <p class="output">显示收到的内容和发送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 = '接受到来自ets的内容:'; var result = event.data; if (typeof(result) === 'string') { console.info(`收到H5的内容, string is: ${result}`); msg = msg + result; } else if (typeof(result) === 'object') { if (result instanceof ArrayBuffer) { console.info(`收到H5, length is: ${result.byteLength}`); msg = msg + 'lenght is ' + result.byteLength; } else { console.info('not support'); } } else { console.info('not support'); } output.innerHTML = msg; } } } }) function PostMsgToEts(data) { if (h5Port) { h5Port.postMessage(data); } else { console.error('H5数据为空'); } } </script> </html>