1# Interface (WebMessagePort) 2 3Implements a **WebMessagePort** to send and receive [WebMessageType](./arkts-apis-webview-e.md#webmessagetype10) or [WebMessage](./arkts-apis-webview-t.md#webmessage) messages to the HTML5 side. 4 5> **NOTE** 6> 7> - The initial APIs of this module are supported since API version 9. Updates will be marked with a superscript to indicate their earliest API version. 8> 9> - The initial APIs of this interface are supported since API version 9. 10> 11> - You can preview how this component looks on a real device, but not in DevEco Studio Previewer. 12 13## Modules to Import 14 15```ts 16import { webview } from '@kit.ArkWeb'; 17``` 18 19## Attributes 20 21**System capability**: SystemCapability.Web.Webview.Core 22 23| Name | Type | Read-Only| Optional| Description | 24| ------------ | ------ | ---- | ---- | ------------------------------------------------| 25| isExtentionType<sup>10+</sup> | boolean | No | Yes| Whether to use the extended interface such as [postMessageEventExt](#postmessageeventext10) and [onMessageEventExt](#onmessageeventext10) when creating a **WebMessagePort**.<br>The value **true** means to use the extended interface, and **false** means the opposite.<br>Default value: **false**. | 26 27## postMessageEvent 28 29postMessageEvent(message: WebMessage): void 30 31Sends a message of the [WebMessage](./arkts-apis-webview-t.md#webmessage) type to the HTML5 side. The [onMessageEvent](#onmessageevent) API must be invoked first. Otherwise, the message fails to be sent. For details about the sample code, see [postMessage](./arkts-apis-webview-WebviewController.md#postmessage). 32 33**System capability**: SystemCapability.Web.Webview.Core 34 35**Parameters** 36 37| Name | Type | Mandatory| Description | 38| ------- | ------ | ---- | :------------- | 39| message | [WebMessage](./arkts-apis-webview-t.md#webmessage) | Yes | Message to send.| 40 41**Error codes** 42 43For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 44 45| Error Code| Error Message | 46| -------- | ------------------------------------- | 47| 17100010 | Failed to post messages through the port. | 48| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 49 50**Example** 51 52```ts 53// xxx.ets 54import { webview } from '@kit.ArkWeb'; 55import { BusinessError } from '@kit.BasicServicesKit'; 56 57@Entry 58@Component 59struct WebComponent { 60 controller: webview.WebviewController = new webview.WebviewController(); 61 ports: webview.WebMessagePort[] = []; 62 63 build() { 64 Column() { 65 Button('postMessageEvent') 66 .onClick(() => { 67 try { 68 this.ports = this.controller.createWebMessagePorts(); 69 this.controller.postMessage('__init_port__', [this.ports[0]], '*'); 70 this.ports[1].postMessageEvent("post message from ets to html5"); 71 } catch (error) { 72 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 73 } 74 }) 75 Web({ src: 'www.example.com', controller: this.controller }) 76 } 77 } 78} 79``` 80 81## onMessageEvent 82 83onMessageEvent(callback: (result: WebMessage) => void): void 84 85Registers a callback on the application message port to receive messages of the [WebMessage](./arkts-apis-webview-t.md#webmessage) type from the HTML5 side. For details about the sample code, see [postMessage](./arkts-apis-webview-WebviewController.md#postmessage). 86 87**System capability**: SystemCapability.Web.Webview.Core 88 89**Parameters** 90 91| Name | Type | Mandatory| Description | 92| -------- | -------- | ---- | :------------------- | 93| callback | (result: [WebMessage](./arkts-apis-webview-t.md#webmessage)) => void | Yes | Message received.| 94 95**Error codes** 96 97For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 98 99| Error Code| Error Message | 100| -------- | ----------------------------------------------- | 101| 17100006 | Failed to register a message event for the port.| 102| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed.| 103 104**Example** 105 106```ts 107// xxx.ets 108import { webview } from '@kit.ArkWeb'; 109import { BusinessError } from '@kit.BasicServicesKit'; 110 111@Entry 112@Component 113struct WebComponent { 114 controller: webview.WebviewController = new webview.WebviewController(); 115 ports: webview.WebMessagePort[] = []; 116 117 build() { 118 Column() { 119 Button('onMessageEvent') 120 .onClick(() => { 121 try { 122 this.ports = this.controller.createWebMessagePorts(); 123 this.ports[1].onMessageEvent((msg) => { 124 if (typeof (msg) == "string") { 125 console.log("received string message from html5, string is:" + msg); 126 } else if (typeof (msg) == "object") { 127 if (msg instanceof ArrayBuffer) { 128 console.log("received arraybuffer from html5, length is:" + msg.byteLength); 129 } else { 130 console.log("not support"); 131 } 132 } else { 133 console.log("not support"); 134 } 135 }) 136 } catch (error) { 137 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 138 } 139 }) 140 Web({ src: 'www.example.com', controller: this.controller }) 141 } 142 } 143} 144``` 145 146## postMessageEventExt<sup>10+</sup> 147 148postMessageEventExt(message: WebMessageExt): void 149 150Sends a message of the [WebMessageType](./arkts-apis-webview-e.md#webmessagetype10) type to the HTML5 side. You must call [onMessageEventExt](#onmessageeventext10) first. Otherwise, the message fails to be sent. For the complete sample code, see [onMessageEventExt](#onmessageeventext10). 151 152**System capability**: SystemCapability.Web.Webview.Core 153 154**Parameters** 155 156| Name | Type | Mandatory| Description | 157| ------- | ------ | ---- | :------------- | 158| message | [WebMessageExt](./arkts-apis-webview-WebMessageExt.md) | Yes | Message to send.| 159 160**Error codes** 161 162For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 163 164| Error Code| Error Message | 165| -------- | ------------------------------------- | 166| 17100010 | Failed to post messages through the port. | 167| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 168 169## onMessageEventExt<sup>10+</sup> 170 171onMessageEventExt(callback: (result: WebMessageExt) => void): void 172 173Registers a callback on the application message port to receive messages of the [WebMessageType](./arkts-apis-webview-e.md#webmessagetype10) type from the HTML5 side. 174 175**System capability**: SystemCapability.Web.Webview.Core 176 177**Parameters** 178 179| Name | Type | Mandatory| Description | 180| -------- | -------- | ---- | :------------------- | 181| callback | (result: [WebMessageExt](./arkts-apis-webview-WebMessageExt.md)) => void | Yes | Message received.| 182 183**Error codes** 184 185For details about the error codes, see [Webview Error Codes](errorcode-webview.md). 186 187| Error Code| Error Message | 188| -------- | ----------------------------------------------- | 189| 17100006 | Failed to register a message event for the port. | 190| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | 191 192**Example** 193 194```ts 195// xxx.ets 196import { webview } from '@kit.ArkWeb'; 197import { BusinessError } from '@kit.BasicServicesKit'; 198 199class TestObj { 200 test(str: string): ArrayBuffer { 201 let buf = new ArrayBuffer(str.length); 202 let buff = new Uint8Array(buf); 203 204 for (let i = 0; i < str.length; i++) { 205 buff[i] = str.charCodeAt(i); 206 } 207 return buf; 208 } 209} 210 211// Example of sending messages between an application and a web page: Use the init_web_messageport channel to receive messages from the web page on the application side through port 0 and receive messages from the application on the web page side through port 1. 212@Entry 213@Component 214struct WebComponent { 215 controller: webview.WebviewController = new webview.WebviewController(); 216 ports: webview.WebMessagePort[] = []; 217 nativePort: webview.WebMessagePort | null = null; 218 @State msg1: string = ""; 219 @State msg2: string = ""; 220 message: webview.WebMessageExt = new webview.WebMessageExt(); 221 @State testObjtest: TestObj = new TestObj(); 222 223 build() { 224 Column() { 225 Text(this.msg1).fontSize(16) 226 Text(this.msg2).fontSize(16) 227 Button('SendToH5 setString').margin({ 228 right: 800, 229 }) 230 .onClick(() => { 231 // Use the local port to send messages to HTML5. 232 try { 233 console.log("In ArkTS side send true start"); 234 if (this.nativePort) { 235 this.message.setType(1); 236 this.message.setString("helloFromEts"); 237 this.nativePort.postMessageEventExt(this.message); 238 } 239 } 240 catch (error) { 241 console.error(`In ArkTS side send message catch error, ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 242 } 243 }) 244 Button('SendToH5 setNumber').margin({ 245 top: 10, 246 right: 800, 247 }) 248 .onClick(() => { 249 // Use the local port to send messages to HTML5. 250 try { 251 console.log("In ArkTS side send true start"); 252 if (this.nativePort) { 253 this.message.setType(2); 254 this.message.setNumber(12345); 255 this.nativePort.postMessageEventExt(this.message); 256 } 257 } 258 catch (error) { 259 console.error(`In ArkTS side send message catch error, ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 260 } 261 }) 262 Button('SendToH5 setBoolean').margin({ 263 top: -90, 264 }) 265 .onClick(() => { 266 // Use the local port to send messages to HTML5. 267 try { 268 console.log("In ArkTS side send true start"); 269 if (this.nativePort) { 270 this.message.setType(3); 271 this.message.setBoolean(true); 272 this.nativePort.postMessageEventExt(this.message); 273 } 274 } 275 catch (error) { 276 console.error(`In ArkTS side send message catch error, ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 277 } 278 }) 279 Button('SendToH5 setArrayBuffer').margin({ 280 top: 10, 281 }) 282 .onClick(() => { 283 // Use the local port to send messages to HTML5. 284 try { 285 console.log("In ArkTS side send true start"); 286 if (this.nativePort) { 287 this.message.setType(4); 288 this.message.setArrayBuffer(this.testObjtest.test("Name=test&Password=test")); 289 this.nativePort.postMessageEventExt(this.message); 290 } 291 } 292 catch (error) { 293 console.error(`In ArkTS side send message catch error, ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 294 } 295 }) 296 Button('SendToH5 setArray').margin({ 297 top: -90, 298 left: 800, 299 }) 300 .onClick(() => { 301 // Use the local port to send messages to HTML5. 302 try { 303 console.log("In ArkTS side send true start"); 304 if (this.nativePort) { 305 this.message.setType(5); 306 this.message.setArray([1, 2, 3]); 307 this.nativePort.postMessageEventExt(this.message); 308 } 309 } 310 catch (error) { 311 console.error(`In ArkTS side send message catch error, ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 312 } 313 }) 314 Button('SendToH5 setError').margin({ 315 top: 10, 316 left: 800, 317 }) 318 .onClick(() => { 319 // Use the local port to send messages to HTML5. 320 try { 321 console.log("In ArkTS side send true start"); 322 throw new ReferenceError("ReferenceError"); 323 } 324 catch (error) { 325 if (this.nativePort) { 326 this.message.setType(6); 327 this.message.setError(error); 328 this.nativePort.postMessageEventExt(this.message); 329 } 330 console.error(`In ArkTS side send message catch error, ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 331 } 332 }) 333 334 Web({ src: $rawfile('index.html'), controller: this.controller }) 335 .onPageEnd(() => { 336 console.log("In ArkTS side message onPageEnd init message channel"); 337 // 1. Create a message port. 338 this.ports = this.controller.createWebMessagePorts(true); 339 // 2. Send port 1 to HTML5. 340 this.controller.postMessage("init_web_messageport", [this.ports[1]], "*"); 341 // 3. Save port 0 to the local host. 342 this.nativePort = this.ports[0]; 343 // 4. Set the callback. 344 this.nativePort.onMessageEventExt((result) => { 345 console.log("In ArkTS side got message"); 346 try { 347 let type = result.getType(); 348 console.log("In ArkTS side getType:" + type); 349 switch (type) { 350 case webview.WebMessageType.STRING: { 351 this.msg1 = "result type:" + typeof (result.getString()); 352 this.msg2 = "result getString:" + ((result.getString())); 353 break; 354 } 355 case webview.WebMessageType.NUMBER: { 356 this.msg1 = "result type:" + typeof (result.getNumber()); 357 this.msg2 = "result getNumber:" + ((result.getNumber())); 358 break; 359 } 360 case webview.WebMessageType.BOOLEAN: { 361 this.msg1 = "result type:" + typeof (result.getBoolean()); 362 this.msg2 = "result getBoolean:" + ((result.getBoolean())); 363 break; 364 } 365 case webview.WebMessageType.ARRAY_BUFFER: { 366 this.msg1 = "result type:" + typeof (result.getArrayBuffer()); 367 this.msg2 = "result getArrayBuffer byteLength:" + ((result.getArrayBuffer().byteLength)); 368 break; 369 } 370 case webview.WebMessageType.ARRAY: { 371 this.msg1 = "result type:" + typeof (result.getArray()); 372 this.msg2 = "result getArray:" + result.getArray(); 373 break; 374 } 375 case webview.WebMessageType.ERROR: { 376 this.msg1 = "result type:" + typeof (result.getError()); 377 this.msg2 = "result getError:" + result.getError(); 378 break; 379 } 380 default: { 381 this.msg1 = "default break, type:" + type; 382 break; 383 } 384 } 385 } 386 catch (error) { 387 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 388 } 389 }); 390 }) 391 } 392 } 393} 394``` 395 396HTML file to be loaded: 397```html 398<!--index.html--> 399<!DOCTYPE html> 400<html lang="en-gb"> 401<head> 402 <title>WebView MessagePort Demo</title> 403</head> 404 405<body> 406<h1>Html5 Send and Receive Message</h1> 407<h3 id="msg">Receive string:</h3> 408<h3 id="msg2">Receive arraybuffer:</h3> 409<div style="font-size: 10pt; text-align: center;"> 410 <input type="button" value="Send String" onclick="postStringToApp();" /><br/> 411</div> 412</body> 413<script src="index.js"></script> 414</html> 415``` 416 417<!--code_no_check--> 418```js 419//index.js 420var h5Port; 421window.addEventListener('message', function(event) { 422 if (event.data == 'init_web_messageport') { 423 if(event.ports[0] != null) { 424 h5Port = event.ports[0]; // 1. Save the port number sent from the eTS side. 425 h5Port.onmessage = function(event) { 426 console.log("hwd In html got message"); 427 // 2. Receive the message sent from the eTS side. 428 var result = event.data; 429 console.log("In html got message, typeof: ", typeof(result)); 430 console.log("In html got message, result: ", (result)); 431 if (typeof(result) == "string") { 432 console.log("In html got message, String: ", result); 433 document.getElementById("msg").innerHTML = "String:" + result; 434 } else if (typeof(result) == "number") { 435 console.log("In html side got message, number: ", result); 436 document.getElementById("msg").innerHTML = "Number:" + result; 437 } else if (typeof(result) == "boolean") { 438 console.log("In html side got message, boolean: ", result); 439 document.getElementById("msg").innerHTML = "Boolean:" + result; 440 } else if (typeof(result) == "object") { 441 if (result instanceof ArrayBuffer) { 442 document.getElementById("msg2").innerHTML = "ArrayBuffer:" + result.byteLength; 443 console.log("In html got message, byteLength: ", result.byteLength); 444 } else if (result instanceof Error) { 445 console.log("In html error message, err:" + (result)); 446 console.log("In html error message, typeof err:" + typeof(result)); 447 document.getElementById("msg2").innerHTML = "Error:" + result.name + ", msg:" + result.message; 448 } else if (result instanceof Array) { 449 console.log("In html got message, Array"); 450 console.log("In html got message, Array length:" + result.length); 451 console.log("In html got message, Array[0]:" + (result[0])); 452 console.log("In html got message, typeof Array[0]:" + typeof(result[0])); 453 document.getElementById("msg2").innerHTML = "Array len:" + result.length + ", value:" + result; 454 } else { 455 console.log("In html got message, not any instance of support type"); 456 document.getElementById("msg").innerHTML = "not any instance of support type"; 457 } 458 } else { 459 console.log("In html got message, not support type"); 460 document.getElementById("msg").innerHTML = "not support type"; 461 } 462 } 463 h5Port.onmessageerror = (event) => { 464 console.error(`hwd In html Error receiving message: ${event}`); 465 }; 466 } 467 } 468}) 469 470// Use h5Port to send a message of the string type to the ets side. 471function postStringToApp() { 472 if (h5Port) { 473 console.log("In html send string message"); 474 h5Port.postMessage("hello"); 475 console.log("In html send string message end"); 476 } else { 477 console.error("In html h5port is null, please init first"); 478 } 479} 480``` 481 482## close 483 484close(): void 485 486Closes this message port when messages do not need to be sent. Before calling this method, call [createWebMessagePorts](./arkts-apis-webview-WebviewController.md#createwebmessageports) to create a message port. 487 488**System capability**: SystemCapability.Web.Webview.Core 489 490**Example** 491 492```ts 493// xxx.ets 494import { webview } from '@kit.ArkWeb'; 495import { BusinessError } from '@kit.BasicServicesKit'; 496 497@Entry 498@Component 499struct WebComponent { 500 controller: webview.WebviewController = new webview.WebviewController(); 501 msgPort: webview.WebMessagePort[] = []; 502 503 build() { 504 Column() { 505 // Use createWebMessagePorts to create a message port. 506 Button('createWebMessagePorts') 507 .onClick(() => { 508 try { 509 this.msgPort = this.controller.createWebMessagePorts(); 510 console.log("createWebMessagePorts size:" + this.msgPort.length) 511 } catch (error) { 512 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 513 } 514 }) 515 Button('close') 516 .onClick(() => { 517 try { 518 if (this.msgPort && this.msgPort.length == 2) { 519 this.msgPort[1].close(); 520 } else { 521 console.error("msgPort is null, Please initialize first"); 522 } 523 } catch (error) { 524 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 525 } 526 }) 527 Web({ src: 'www.example.com', controller: this.controller }) 528 } 529 } 530} 531``` 532