• 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
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        // Display the content received from the HTML side.
27        Text(this.receivedFromHtml)
28        // Send the content in the text box to the HTML side.
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. Create two message ports.
38              this.ports = this.controller.createWebMessagePorts();
39              // 2. Register a callback for the message port (for example, port 1) on the application.
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. Send the other message port (for example, port 0) to the HTML side, which then saves the message port.
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. Use the message port on the application to send messages to the message port that has been sent to the HTML side.
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- Frontend page code:
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  <body>
94      <h1>WebView Message Port Demo</h1>
95      <div>
96          <input type="button" value="SendToEts" onclick="PostMsgToEts(msgFromJS.value);"/><br/>
97          <input id="msgFromJS" type="text" value="send this message from HTML to ets"/><br/>
98      </div>
99      <p class="output">display received message send from ets</p>
100  </body>
101  <script>
102  var h5Port;
103  var output = document.querySelector('.output');
104  window.addEventListener('message', function (event) {
105      if (event.data === '__init_port__') {
106          if (event.ports[0] !== null) {
107              h5Port = event.ports[0]; // 1. Save the port sent from the eTS side.
108              h5Port.onmessage = function (event) {
109                // 2. Receive messages sent from the eTS side.
110                var msg = 'Got message from ets:';
111                var result = event.data;
112                if (typeof(result) === 'string') {
113                  console.info(`received string message from html5, string is: ${result}`);
114                  msg = msg + result;
115                } else if (typeof(result) === 'object') {
116                  if (result instanceof ArrayBuffer) {
117                    console.info(`received arraybuffer from html5, length is: ${result.byteLength}`);
118                    msg = msg + 'lenght is ' + result.byteLength;
119                  } else {
120                    console.info('not support');
121                  }
122                } else {
123                  console.info('not support');
124                }
125                output.innerHTML = msg;
126              }
127          }
128      }
129  })
130
131  // 3. Use H5Port to send messages to the eTS side.
132  function PostMsgToEts(data) {
133      if (h5Port) {
134        h5Port.postMessage(data);
135      } else {
136        console.error('h5Port is null, Please initialize first');
137      }
138  }
139  </script>
140  </html>
141  ```
142