• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Establishing a Data Channel Between the Application and the Frontend Page
2
3
4The [createWebMessagePorts()](../reference/apis/js-apis-webview.md#createwebmessageports) API allows you to create message ports to implement communication between the application and frontend page.
5
6
7In the following example, **createWebMessagePorts** is used to create message ports on the application and [postMessage()](../reference/apis/js-apis-webview.md#postmessage) is used to forward one of the message ports to the frontend page so that the application and frontend page can exchange messages with each other over the port.
8
9
10- Application code:
11
12  ```ts
13  // xxx.ets
14  import web_webview from '@ohos.web.webview';
15  import business_error from '@ohos.base';
16
17  @Entry
18  @Component
19  struct WebComponent {
20    controller: web_webview.WebviewController = new web_webview.WebviewController();
21    ports: web_webview.WebMessagePort[] = [];
22    @State sendFromEts: string = 'Send this message from ets to HTML';
23    @State receivedFromHtml: string = 'Display received message send from HTML';
24
25    build() {
26      Column() {
27        // Display the content received from the HTML side.
28        Text(this.receivedFromHtml)
29        // Send the content in the text box to the HTML side.
30        TextInput({placeholder: 'Send this message from ets to HTML'})
31          .onChange((value: string) => {
32            this.sendFromEts = value;
33          })
34
35        Button('postMessage')
36          .onClick(() => {
37            try {
38              // 1. Create two message ports.
39              this.ports = this.controller.createWebMessagePorts();
40              // 2. Register a callback for the message port (for example, port 1) on the application.
41              this.ports[1].onMessageEvent((result: web_webview.WebMessage) => {
42                let msg = 'Got msg from HTML:';
43                if (typeof(result) === 'string') {
44                  console.info(`received string message from html5, string is: ${result}`);
45                  msg = msg + result;
46                } else if (typeof(result) === 'object') {
47                  if (result instanceof ArrayBuffer) {
48                    console.info(`received arraybuffer from html5, length is: ${result.byteLength}`);
49                    msg = msg + 'lenght is ' + result.byteLength;
50                  } else {
51                    console.info('not support');
52                  }
53                } else {
54                  console.info('not support');
55                }
56                this.receivedFromHtml = msg;
57              })
58              // 3. Send the other message port (for example, port 0) to the HTML side, which then saves the message port.
59              this.controller.postMessage('__init_port__', [this.ports[0]], '*');
60            } catch (error) {
61              let e: business_error.BusinessError = error as business_error.BusinessError;
62              console.error(`ErrorCode: ${e.code},  Message: ${e.message}`);
63            }
64          })
65
66        // 4. Use the message port on the application to send messages to the message port that has been sent to the HTML side.
67        Button('SendDataToHTML')
68          .onClick(() => {
69            try {
70              if (this.ports && this.ports[1]) {
71                this.ports[1].postMessageEvent(this.sendFromEts);
72              } else {
73                console.error(`ports is null, Please initialize first`);
74              }
75            } catch (error) {
76              let e: business_error.BusinessError = error as business_error.BusinessError;
77              console.error(`ErrorCode: ${e.code},  Message: ${e.message}`);
78            }
79          })
80        Web({ src: $rawfile('xxx.html'), controller: this.controller })
81      }
82    }
83  }
84  ```
85
86- Frontend page code:
87
88  ```html
89  <!--xxx.html-->
90  <!DOCTYPE html>
91  <html>
92  <head>
93      <meta name="viewport" content="width=device-width, initial-scale=1.0">
94      <title>WebView Message Port Demo</title>
95  </head>
96  <body>
97      <h1>WebView Message Port Demo</h1>
98      <div>
99          <input type="button" value="SendToEts" onclick="PostMsgToEts(msgFromJS.value);"/><br/>
100          <input id="msgFromJS" type="text" value="send this message from HTML to ets"/><br/>
101      </div>
102      <p class="output">display received message send from ets</p>
103  </body>
104  <script>
105  var h5Port;
106  var output = document.querySelector('.output');
107  window.addEventListener('message', function (event) {
108      if (event.data === '__init_port__') {
109          if (event.ports[0] !== null) {
110              h5Port = event.ports[0]; // 1. Save the port number sent from the application side.
111              h5Port.onmessage = function (event) {
112                // 2. Receive messages sent from the eTS side.
113                var msg = 'Got message from ets:';
114                var result = event.data;
115                if (typeof(result) === 'string') {
116                  console.info(`received string message from html5, string is: ${result}`);
117                  msg = msg + result;
118                } else if (typeof(result) === 'object') {
119                  if (result instanceof ArrayBuffer) {
120                    console.info(`received arraybuffer from html5, length is: ${result.byteLength}`);
121                    msg = msg + 'lenght is ' + result.byteLength;
122                  } else {
123                    console.info('not support');
124                  }
125                } else {
126                  console.info('not support');
127                }
128                output.innerHTML = msg;
129              }
130          }
131      }
132  })
133
134  // 3. Use h5Port to send messages to the application side.
135  function PostMsgToEts(data) {
136      if (h5Port) {
137        h5Port.postMessage(data);
138      } else {
139        console.error('h5Port is null, Please initialize first');
140      }
141  }
142  </script>
143  </html>
144  ```
145