UNPKG

2.32 kBPlain TextView Raw
1/**
2 * @license
3 * Copyright 2017 Google Inc.
4 * SPDX-License-Identifier: Apache-2.0
5 */
6
7import type {Protocol} from 'devtools-protocol';
8
9import {assert} from '../util/assert.js';
10
11/**
12 * Dialog instances are dispatched by the {@link Page} via the `dialog` event.
13 *
14 * @remarks
15 *
16 * @example
17 *
18 * ```ts
19 * import puppeteer from 'puppeteer';
20 *
21 * (async () => {
22 * const browser = await puppeteer.launch();
23 * const page = await browser.newPage();
24 * page.on('dialog', async dialog => {
25 * console.log(dialog.message());
26 * await dialog.dismiss();
27 * await browser.close();
28 * });
29 * page.evaluate(() => alert('1'));
30 * })();
31 * ```
32 *
33 * @public
34 */
35export abstract class Dialog {
36 #type: Protocol.Page.DialogType;
37 #message: string;
38 #defaultValue: string;
39 /**
40 * @internal
41 */
42 protected handled = false;
43
44 /**
45 * @internal
46 */
47 constructor(
48 type: Protocol.Page.DialogType,
49 message: string,
50 defaultValue = '',
51 ) {
52 this.#type = type;
53 this.#message = message;
54 this.#defaultValue = defaultValue;
55 }
56
57 /**
58 * The type of the dialog.
59 */
60 type(): Protocol.Page.DialogType {
61 return this.#type;
62 }
63
64 /**
65 * The message displayed in the dialog.
66 */
67 message(): string {
68 return this.#message;
69 }
70
71 /**
72 * The default value of the prompt, or an empty string if the dialog
73 * is not a `prompt`.
74 */
75 defaultValue(): string {
76 return this.#defaultValue;
77 }
78
79 /**
80 * @internal
81 */
82 protected abstract handle(options: {
83 accept: boolean;
84 text?: string;
85 }): Promise<void>;
86
87 /**
88 * A promise that resolves when the dialog has been accepted.
89 *
90 * @param promptText - optional text that will be entered in the dialog
91 * prompt. Has no effect if the dialog's type is not `prompt`.
92 *
93 */
94 async accept(promptText?: string): Promise<void> {
95 assert(!this.handled, 'Cannot accept dialog which is already handled!');
96 this.handled = true;
97 await this.handle({
98 accept: true,
99 text: promptText,
100 });
101 }
102
103 /**
104 * A promise which will resolve once the dialog has been dismissed
105 */
106 async dismiss(): Promise<void> {
107 assert(!this.handled, 'Cannot dismiss dialog which is already handled!');
108 this.handled = true;
109 await this.handle({
110 accept: false,
111 });
112 }
113}