• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Displaying Web Page Dialog Boxes
2
3In HTML, JavaScript can be used to create the following types of dialog boxes: **window.alert(message)**, **window.confirm(message)**, and **window.prompt(message, defaultValue)**. These dialog boxes can be used to convey information, confirm operations, or request input from users.
4
5Currently, ArkWeb does not provide default dialog boxes. To ensure that the dialog box of a web page can be used properly, the application needs to customize the dialog box through the [onAlert](../reference/apis-arkweb/arkts-basic-components-web-events.md#onalert), [onConfirm](../reference/apis-arkweb/arkts-basic-components-web-events.md#onconfirm), and [onPrompt](../reference/apis-arkweb/arkts-basic-components-web-events.md#onprompt9) APIs.
6
7## Implementing the Alert Dialog Box
8
9You can use **window.alert()** to display a dialog box that contains optional information. The alert dialog box is used to ensure that users can obtain certain information. When the alert dialog box is displayed, the user needs to click **OK** to continue the operation.
10- The optional parameter **message** is a string to be displayed in the alert dialog box. If other types of values are passed, the values will be converted to strings.
11- This method does not return any value.
12
13An application can listen for the **alert** method of a web page through the [onAlert](../reference/apis-arkweb/arkts-basic-components-web-events.md#onalert) event and create a dialog box.
14
15- Create a dialog box using [AlertDialog](../reference/apis-arkui/arkui-ts/ts-methods-alert-dialog-box.md).
16
17  ```ts
18  import { webview } from '@kit.ArkWeb';
19
20  @Entry
21  @Component
22  struct Index {
23    @State message: string = 'Hello World';
24    webviewController: webview.WebviewController = new webview.WebviewController();
25    uiContext: UIContext = this.getUIContext();
26
27    build() {
28      Row() {
29        Web({ src: $rawfile('test.html'), controller: this.webviewController })
30          .onAlert((event) => {
31            if (event) {
32              console.log("event.url:" + event.url);
33              console.log("event.message:" + event.message);
34              this.uiContext.showAlertDialog({
35                title: "Alert from " + event.url + "",
36                message: event.message,
37                confirm:{
38                  value: "OK",
39                  action: ()=>{
40                    console.info('Alert confirmed.');
41                    event.result.handleConfirm();
42                  }
43                },
44                cancel: () => {
45                  event.result.handleCancel();
46                }
47              })
48            }
49            return true;
50          })
51      }
52    }
53  }
54  ```
55  Loaded HTML:
56  ```html
57  <!doctype html>
58  <html lang="en">
59  <head>
60      <meta charset="UTF-8">
61      <meta name="viewport"
62            content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
63      <meta http-equiv="X-UA-Compatible" content="ie=edge">
64      <title>Document</title>
65      <style>
66          button,label,input {
67          margin: 5px 0;
68          }
69      </style>
70  </head>
71  <body>
72  <input type="text" id="alert-message" placeholder="message for alert"><br/>
73  <button onclick="handleAlert()">alert</button><br/>
74  <script>
75      function handleAlert() {
76          let message = document.getElementById("alert-message").value;
77          let result = window.alert(message ? message : 'alert');
78      }
79  </script>
80  </body>
81  </html>
82  ```
83
84- Create a dialog box using [CustomDialog-AlertDialog](../reference/apis-arkui/arkui-ts/ohos-arkui-advanced-Dialog.md#alertdialog).
85
86  ```ts
87  import { AlertDialog, router } from '@kit.ArkUI';
88  import { webview } from '@kit.ArkWeb';
89
90  @Entry
91  @Component
92  struct AlertDialogPage {
93    @State message: string = 'Hello World';
94    @State title: string = 'Hello World';
95    @State subtitle: string = '';
96    @State result: JsResult | null = null;
97    webviewController: webview.WebviewController = new webview.WebviewController();
98    dialogControllerAlert: CustomDialogController = new CustomDialogController({
99      builder: AlertDialog({
100        primaryTitle: this.title,
101        secondaryTitle: this.subtitle,
102        content: this.message,
103        primaryButton: {
104          value: 'OK',
105          role: ButtonRole.ERROR,
106          action: () => {
107            console.info('Callback when the second button is clicked');
108            this.result?.handleConfirm();
109          }
110        },
111      }),
112      onWillDismiss: ()=>{
113        this.result?.handleCancel();
114        this.dialogControllerAlert.close();
115      }
116    })
117
118    build() {
119      Column() {
120        Button('back').onClick((event: ClickEvent) => {
121          this.getUIContext().getRouter().back();
122        })
123        Web({ src: $rawfile('alert.html'), controller: this.webviewController })
124          .onAlert((event) => {
125            if (event) {
126              console.log("event.url:" + event.url);
127              console.log("event.message:" + event.message);
128              this.title = "Alert from " + event.url + "";
129              this.message = event.message;
130              this.result = event.result;
131              this.dialogControllerAlert.open();
132            }
133            return true;
134          })
135      }
136    }
137  }
138  ```
139  Loaded HTML:
140  ```html
141  <!doctype html>
142  <html lang="en">
143  <head>
144      <meta charset="UTF-8">
145      <meta name="viewport"
146            content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
147      <meta http-equiv="X-UA-Compatible" content="ie=edge">
148      <title>Document</title>
149      <style>
150          button,label,input {
151          margin: 5px 0;
152          }
153      </style>
154  </head>
155  <body>
156  <input type="text" id="alert-message" placeholder="message for alert"><br/>
157  <button onclick="handleAlert()">alert</button><br/>
158  <script>
159      function handleAlert() {
160          let message = document.getElementById("alert-message").value;
161          let result = window.alert(message ? message : 'alert');
162      }
163  </script>
164  </body>
165  </html>
166  ```
167
168  ![AlertDialog](./figures/web-alert-dialog.gif)
169
170## Implementing the Confirm Dialog Box
171
172You can use **window.confirm()** to display a dialog box that contains optional messages and waits for the user to confirm or cancel it.
173- The optional parameter **message** is a string to be displayed in the dialog box. If other types of values are passed, the values will be converted to strings.
174- This method returns a Boolean value, indicating whether OK (**true**) or Cancel (**false**) is selected. If the application ignores the dialog box on the page, the return value is always **false**.
175
176The confirm dialog box is used to check whether the user accepts an operation such as leaving a web page to prevent data loss.
177
178An application can listen for the **confirm** method of a web page through the [onConfirm](../reference/apis-arkweb/arkts-basic-components-web-events.md#onconfirm) event and create a dialog box.
179
180- Create a dialog box using [AlertDialog](../reference/apis-arkui/arkui-ts/ts-methods-alert-dialog-box.md).
181
182  ```ts
183  import { webview } from '@kit.ArkWeb';
184
185  @Entry
186  @Component
187  struct Index {
188    @State message: string = 'Hello World';
189    webviewController: webview.WebviewController = new webview.WebviewController();
190    uiContext: UIContext = this.getUIContext();
191
192    build() {
193      Column() {
194        Web({ src: $rawfile('test.html'), controller: this.webviewController })
195          .onConfirm((event) => {
196            if (event) {
197              console.log("event.url:" + event.url);
198              console.log("event.message:" + event.message);
199              this.uiContext.showAlertDialog({
200                title: "Message from " + event.url + "",
201                message: event.message,
202                primaryButton: {
203                  value: 'cancel',
204                  action: () => {
205                    event.result.handleCancel();
206                  }
207                },
208                secondaryButton: {
209                  value: 'ok',
210                  action: () => {
211                    event.result.handleConfirm();
212                  }
213                },
214                cancel: () => {
215                  event.result.handleCancel();
216                }
217              })
218            }
219            return true;
220          })
221      }
222    }
223  }
224  ```
225
226  Loaded HTML:
227  ```html
228  <!doctype html>
229  <html lang="en">
230  <head>
231      <meta charset="UTF-8">
232      <meta name="viewport"
233            content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
234      <meta http-equiv="X-UA-Compatible" content="ie=edge">
235      <title>Document</title>
236      <style>
237          button,label,input {
238          margin: 5px 0;
239          }
240      </style>
241  </head>
242  <body>
243  result: <label id="confirmLabel" for="confirm"></label><br/>
244  <input type="text" id="confirm-message" placeholder="message for confirm"><br/>
245  <button id="confirm" onclick="handleConfirm()">confirm</button><br/>
246  <script>
247      function handleConfirm() {
248          let message = document.getElementById("confirm-message").value;
249          let result = window.confirm(message ? message : 'confirm');
250          console.log(result);
251          document.getElementById("confirmLabel").innerHTML=String(result);
252      }
253  </script>
254  </body>
255  </html>
256  ```
257
258- Create a dialog box using [CustomDialog-ConfirmDialog](../reference/apis-arkui/arkui-ts/ohos-arkui-advanced-Dialog.md#confirmdialog).
259
260  ```ts
261  import { webview } from '@kit.ArkWeb';
262  import { ConfirmDialog } from '@kit.ArkUI';
263
264  @Entry
265  @Component
266  struct DialogConfirmDialog {
267    @State message: string = 'Hello World';
268    @State title: string = 'Hello World';
269    @State result: JsResult | null = null;
270    webviewController: webview.WebviewController = new webview.WebviewController();
271    isChecked = false;
272    dialogControllerCheckBox: CustomDialogController = new CustomDialogController({
273      builder: ConfirmDialog({
274        title: this.title,
275        content: this.message,
276        // Selected state of the check box
277        isChecked: this.isChecked,
278        // Content of the check box
279        checkTips: 'Do not ask again after denying',
280        primaryButton: {
281          value: 'Disable',
282          action: () => {
283            this.result?.handleCancel();
284          },
285        },
286        secondaryButton: {
287          value: 'Allow',
288          action: () => {
289            this.isChecked = false;
290            console.info('Callback when the second button is clicked');
291            this.result?.handleConfirm();
292          }
293        },
294        onCheckedChange: (checked) => {
295          this.isChecked = checked;
296          console.info('Callback when the checkbox is clicked');
297        },
298      }),
299      onWillDismiss: () => {
300        this.result?.handleCancel();
301        this.dialogControllerCheckBox.close();
302      },
303      autoCancel: true
304    })
305
306    build() {
307      Column() {
308        Web({ src: $rawfile('confirm.html'), controller: this.webviewController })
309          .onConfirm((event) => {
310            if (event) {
311              if (this.isChecked) {
312                event.result.handleCancel();
313              } else {
314                console.log("event.url:" + event.url);
315                console.log("event.message:" + event.message);
316                this.title = "Message from " + event.url + "";
317                this.message = event.message;
318                this.result = event.result;
319                this.dialogControllerCheckBox.open();
320              }
321            }
322            return true;
323          })
324      }
325    }
326  }
327  ```
328  Loaded HTML:
329  ```html
330  <!doctype html>
331  <html lang="en">
332  <head>
333      <meta charset="UTF-8">
334      <meta name="viewport"
335            content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
336      <meta http-equiv="X-UA-Compatible" content="ie=edge">
337      <title>Document</title>
338      <style>
339          button,label,input {
340          margin: 5px 0;
341          }
342      </style>
343  </head>
344  <body>
345  result: <label id="confirmLabel" for="confirm"></label><br/>
346  <input type="text" id="confirm-message" placeholder="message for confirm"><br/>
347  <button id="confirm" onclick="handleConfirm()">confirm</button><br/>
348  <script>
349      function handleConfirm() {
350          let message = document.getElementById("confirm-message").value;
351          let result = window.confirm(message ? message : 'confirm');
352          console.log(result);
353          document.getElementById("confirmLabel").innerHTML=String(result);
354      }
355  </script>
356  </body>
357  </html>
358  ```
359
360  ![ConfirmDialog](./figures/web-confirm-dialog.gif)
361
362## Implementing the Prompt Dialog Box
363
364You can use **window.prompt()** to display a dialog box and wait for the user to submit text or cancel the dialog box. The user needs to input a value and then click **OK **or **Cancel**. If **OK** is clicked, the input value is returned. If **Cancel** is clicked, **null** is returned.
365- The optional parameter **message** is a text displayed to the user. If no message is required, this parameter can be ignored.
366- The optional parameter **defaultValue** is a string that contains the default value displayed in the text input field.
367- The return value is a string of the text input by the user or **null**.
368
369The prompt box is used to prompt users to input a value, which is usually used in scenarios where users need to input a temporary password or verification code.
370
371An application can listen for the **prompt** method of a web page through the [onPrompt](../reference/apis-arkweb/arkts-basic-components-web-events.md#onprompt9) event and create a dialog box.
372
373- Create a dialog box using [CustomDialog-CustomContentDialog](../reference/apis-arkui/arkui-ts/ohos-arkui-advanced-Dialog.md#customcontentdialog12).
374
375  ```ts
376  import { CustomContentDialog } from '@kit.ArkUI';
377  import { webview } from '@kit.ArkWeb';
378
379  @Entry
380  @Component
381  struct PromptDialog {
382    @State message: string = 'Hello World';
383    @State title: string = 'Hello World';
384    @State result: JsResult | null = null;
385    promptResult: string = '';
386    webviewController: webview.WebviewController = new webview.WebviewController();
387    dialogController: CustomDialogController = new CustomDialogController({
388      builder: CustomContentDialog({
389        primaryTitle: this.title,
390        contentBuilder: () => {
391          this.buildContent();
392        },
393        buttons: [
394          {
395            value: 'Cancel',
396            buttonStyle: ButtonStyleMode.TEXTUAL,
397            action: () => {
398              console.info('Callback when the button is clicked');
399              this.result?.handleCancel();
400            }
401          },
402          {
403            value: 'OK',
404            buttonStyle: ButtonStyleMode.TEXTUAL,
405            action: () => {
406              this.result?.handlePromptConfirm(this.promptResult);
407            }
408          }
409        ],
410      }),
411      onWillDismiss: () => {
412        this.result?.handleCancel();
413        this.dialogController.close();
414      }
415    });
416
417    // Custom content area of the dialog box
418    @Builder
419    buildContent(): void {
420      Column() {
421        Text(this.message)
422        TextInput()
423          .onChange((value) => {
424            this.promptResult = value;
425          })
426          .defaultFocus(true)
427      }
428      .width('100%')
429    }
430
431    build() {
432      Column() {
433        Web({ src: $rawfile('prompt.html'), controller: this.webviewController })
434          .onPrompt((event) => {
435            if (event) {
436              console.log("event.url:" + event.url);
437              console.log("event.message:" + event.message);
438              console.log("event.value:" + event.value);
439              this.title = "Message from " + event.url + "";
440              this.message = event.message;
441              this.promptResult = event.value;
442              this.result = event.result;
443              this.dialogController.open();
444            }
445            return true;
446          })
447      }
448    }
449  }
450  ```
451  Loaded HTML:
452  ```html
453  <!doctype html>
454  <html lang="en">
455  <head>
456      <meta charset="UTF-8">
457      <meta name="viewport"
458            content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
459      <meta http-equiv="X-UA-Compatible" content="ie=edge">
460      <title>Document</title>
461      <style>
462          button,label,input {
463          margin: 5px 0;
464          }
465      </style>
466  </head>
467  <body>
468  result: <label id="promptLabel" for="prompt"></label><br/>
469  <input type="text" id="prompt-message" placeholder="message for prompt"><br/>
470  <input type="text" id="prompt-value" placeholder="default value for prompt"><br/>
471  <button id="prompt" onclick="handlePrompt()">prompt</button><br/>
472  <script>
473      function handlePrompt() {
474          let message = document.getElementById("prompt-message").value;
475          let defaultValue = document.getElementById("prompt-value").value;
476          let result = window.prompt(message ? message : 'prompt', defaultValue);
477          console.log(result);
478          document.getElementById("promptLabel").innerHTML=result;
479      }
480  </script>
481  </body>
482  </html>
483  ```
484
485  ![PromptDialog](./figures/web-prompt-dialog.gif)
486