playwright_core/protocol/
dialog.rs

1// Copyright 2024 Paul Adamson
2// Licensed under the Apache License, Version 2.0
3//
4// Dialog protocol object
5//
6// Represents a browser dialog (alert, confirm, prompt, or beforeunload)
7// dispatched via page.on('dialog') events.
8
9use crate::channel_owner::{ChannelOwner, ChannelOwnerImpl, ParentOrConnection};
10use crate::error::Result;
11use serde_json::{json, Value};
12use std::any::Any;
13use std::sync::Arc;
14
15/// Dialog represents a browser dialog (alert, confirm, prompt, or beforeunload).
16///
17/// Dialogs are dispatched via the page.on('dialog') event. Dialogs must be
18/// explicitly accepted or dismissed, otherwise the page will freeze waiting
19/// for the dialog to be handled.
20///
21/// See module-level documentation for usage examples.
22///
23/// See: <https://playwright.dev/docs/api/class-dialog>
24#[derive(Clone)]
25pub struct Dialog {
26    base: ChannelOwnerImpl,
27}
28
29impl Dialog {
30    /// Creates a new Dialog from protocol initialization
31    ///
32    /// This is called by the object factory when the server sends a `__create__` message
33    /// for a Dialog object.
34    pub fn new(
35        parent: Arc<dyn ChannelOwner>,
36        type_name: String,
37        guid: Arc<str>,
38        initializer: Value,
39    ) -> Result<Self> {
40        let base = ChannelOwnerImpl::new(
41            ParentOrConnection::Parent(parent),
42            type_name,
43            guid,
44            initializer,
45        );
46
47        Ok(Self { base })
48    }
49
50    /// Returns the dialog's type.
51    ///
52    /// Returns one of:
53    /// - "alert" - Simple notification dialog
54    /// - "confirm" - Yes/No confirmation dialog
55    /// - "prompt" - Text input dialog
56    /// - "beforeunload" - Page unload confirmation dialog
57    ///
58    /// See: <https://playwright.dev/docs/api/class-dialog#dialog-type>
59    pub fn type_(&self) -> &str {
60        self.initializer()
61            .get("type")
62            .and_then(|v| v.as_str())
63            .unwrap_or("")
64    }
65
66    /// Returns the message displayed in the dialog.
67    ///
68    /// See: <https://playwright.dev/docs/api/class-dialog#dialog-message>
69    pub fn message(&self) -> &str {
70        self.initializer()
71            .get("message")
72            .and_then(|v| v.as_str())
73            .unwrap_or("")
74    }
75
76    /// Returns the default value for prompt dialogs.
77    ///
78    /// For prompt dialogs, returns the default input value.
79    /// For other dialog types (alert, confirm, beforeunload), returns an empty string.
80    ///
81    /// See: <https://playwright.dev/docs/api/class-dialog#dialog-default-value>
82    pub fn default_value(&self) -> &str {
83        self.initializer()
84            .get("defaultValue")
85            .and_then(|v| v.as_str())
86            .unwrap_or("")
87    }
88
89    /// Accepts the dialog.
90    ///
91    /// For prompt dialogs, optionally provides text input.
92    /// For other dialog types, the promptText parameter is ignored.
93    ///
94    /// # Arguments
95    ///
96    /// * `prompt_text` - Optional text to enter in a prompt dialog
97    ///
98    /// # Errors
99    ///
100    /// Returns error if:
101    /// - Dialog has already been accepted or dismissed
102    /// - Communication with browser process fails
103    ///
104    /// See: <https://playwright.dev/docs/api/class-dialog#dialog-accept>
105    pub async fn accept(&self, prompt_text: Option<&str>) -> Result<()> {
106        let params = if let Some(text) = prompt_text {
107            json!({ "promptText": text })
108        } else {
109            json!({})
110        };
111
112        self.channel().send_no_result("accept", params).await?;
113
114        Ok(())
115    }
116
117    /// Dismisses the dialog.
118    ///
119    /// For confirm dialogs, this is equivalent to clicking "Cancel".
120    /// For prompt dialogs, this is equivalent to clicking "Cancel".
121    ///
122    /// # Errors
123    ///
124    /// Returns error if:
125    /// - Dialog has already been accepted or dismissed
126    /// - Communication with browser process fails
127    ///
128    /// See: <https://playwright.dev/docs/api/class-dialog#dialog-dismiss>
129    pub async fn dismiss(&self) -> Result<()> {
130        self.channel().send_no_result("dismiss", json!({})).await?;
131
132        Ok(())
133    }
134}
135
136impl ChannelOwner for Dialog {
137    fn guid(&self) -> &str {
138        self.base.guid()
139    }
140
141    fn type_name(&self) -> &str {
142        self.base.type_name()
143    }
144
145    fn parent(&self) -> Option<Arc<dyn ChannelOwner>> {
146        self.base.parent()
147    }
148
149    fn connection(&self) -> Arc<dyn crate::connection::ConnectionLike> {
150        self.base.connection()
151    }
152
153    fn initializer(&self) -> &Value {
154        self.base.initializer()
155    }
156
157    fn channel(&self) -> &crate::channel::Channel {
158        self.base.channel()
159    }
160
161    fn dispose(&self, reason: crate::channel_owner::DisposeReason) {
162        self.base.dispose(reason)
163    }
164
165    fn adopt(&self, child: Arc<dyn ChannelOwner>) {
166        self.base.adopt(child)
167    }
168
169    fn add_child(&self, guid: Arc<str>, child: Arc<dyn ChannelOwner>) {
170        self.base.add_child(guid, child)
171    }
172
173    fn remove_child(&self, guid: &str) {
174        self.base.remove_child(guid)
175    }
176
177    fn on_event(&self, _method: &str, _params: Value) {
178        // Dialog doesn't emit events
179    }
180
181    fn was_collected(&self) -> bool {
182        self.base.was_collected()
183    }
184
185    fn as_any(&self) -> &dyn Any {
186        self
187    }
188}
189
190impl std::fmt::Debug for Dialog {
191    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
192        f.debug_struct("Dialog")
193            .field("guid", &self.guid())
194            .field("type", &self.type_())
195            .field("message", &self.message())
196            .field("default_value", &self.default_value())
197            .finish()
198    }
199}