1# 建立应用侧与前端页面数据通道 2 3 4前端页面和应用侧之间可以用[createWebMessagePorts()](../reference/apis/js-apis-webview.md#createwebmessageports)接口创建消息端口来实现两端的通信。 5 6 7在下面的示例中,用侧页面中通过createWebMessagePorts方法创建消息端口,再把其中一个端口通过[postMessage()](../reference/apis/js-apis-webview.md#postmessage)接口发送到前端页面,便可以在前端页面和应用侧之间互相发送消息。 8 9 10- 应用侧代码。 11 12 ```ts 13 // xxx.ets 14 import web_webview from '@ohos.web.webview'; 15 16 @Entry 17 @Component 18 struct WebComponent { 19 controller: web_webview.WebviewController = new web_webview.WebviewController(); 20 ports: web_webview.WebMessagePort[]; 21 @State sendFromEts: string = 'Send this message from ets to HTML'; 22 @State receivedFromHtml: string = 'Display received message send from HTML'; 23 24 build() { 25 Column() { 26 // 展示接收到的来自HTML的内容 27 Text(this.receivedFromHtml) 28 // 输入框的内容发送到html 29 TextInput({placeholder: 'Send this message from ets to HTML'}) 30 .onChange((value: string) => { 31 this.sendFromEts = value; 32 }) 33 34 Button('postMessage') 35 .onClick(() => { 36 try { 37 // 1、创建两个消息端口。 38 this.ports = this.controller.createWebMessagePorts(); 39 // 2、在应用侧的消息端口(如端口1)上注册回调事件。 40 this.ports[1].onMessageEvent((result: web_webview.WebMessage) => { 41 let msg = 'Got msg from HTML:'; 42 if (typeof(result) === 'string') { 43 console.info(`received string message from html5, string is: ${result}`); 44 msg = msg + result; 45 } else if (typeof(result) === 'object') { 46 if (result instanceof ArrayBuffer) { 47 console.info(`received arraybuffer from html5, length is: ${result.byteLength}`); 48 msg = msg + 'lenght is ' + result.byteLength; 49 } else { 50 console.info('not support'); 51 } 52 } else { 53 console.info('not support'); 54 } 55 this.receivedFromHtml = msg; 56 }) 57 // 3、将另一个消息端口(如端口0)发送到HTML侧,由HTML侧保存并使用。 58 this.controller.postMessage('__init_port__', [this.ports[0]], '*'); 59 } catch (error) { 60 console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); 61 } 62 }) 63 64 // 4、使用应用侧的端口给另一个已经发送到html的端口发送消息。 65 Button('SendDataToHTML') 66 .onClick(() => { 67 try { 68 if (this.ports && this.ports[1]) { 69 this.ports[1].postMessageEvent(this.sendFromEts); 70 } else { 71 console.error(`ports is null, Please initialize first`); 72 } 73 } catch (error) { 74 console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); 75 } 76 }) 77 Web({ src: $rawfile('xxx.html'), controller: this.controller }) 78 } 79 } 80 } 81 ``` 82 83- 前端页面代码。 84 85 ```html 86 <!--xxx.html--> 87 <!DOCTYPE html> 88 <html> 89 <head> 90 <meta name="viewport" content="width=device-width, initial-scale=1.0"> 91 <title>WebView Message Port Demo</title> 92 </head> 93 94 <script> 95 var h5Port; 96 var output = document.querySelector('.output'); 97 window.addEventListener('message', function (event) { 98 if (event.data === '__init_port__') { 99 if (event.ports[0] !== null) { 100 h5Port = event.ports[0]; // 1. 保存从ets侧发送过来的端口 101 h5Port.onmessage = function (event) { 102 // 2. 接收ets侧发送过来的消息. 103 var msg = 'Got message from ets:'; 104 var result = event.data; 105 if (typeof(result) === 'string') { 106 console.info(`received string message from html5, string is: ${result}`); 107 msg = msg + result; 108 } else if (typeof(result) === 'object') { 109 if (result instanceof ArrayBuffer) { 110 console.info(`received arraybuffer from html5, length is:` ${result.byteLength}`); 111 msg = msg + 'lenght is ' + result.byteLength; 112 } else { 113 console.info('not support'); 114 } 115 } else { 116 console.info('not support'); 117 } 118 output.innerHTML = msg; 119 } 120 } 121 } 122 }) 123 124 // 3. 使用h5Port往ets侧发送消息. 125 function PostMsgToEts(data) { 126 if (h5Port) { 127 h5Port.postMessage(data); 128 } else { 129 console.error('h5Port is null, Please initialize first'); 130 } 131 } 132 </script> 133 134 <body> 135 <h1>WebView Message Port Demo</h1> 136 <div> 137 <input type="button" value="SendToEts" onclick="PostMsgToEts(msgFromJS.value);"/><br/> 138 <input id="msgFromJS" type="text" value="send this message from HTML to ets"/><br/> 139 </div> 140 <p class="output">display received message send from ets</p> 141 </body> 142 </html> 143 ``` 144