Skip to main content

playwright_rs/protocol/
console_message.rs

1// Copyright 2026 Paul Adamson
2// Licensed under the Apache License, Version 2.0
3//
4// ConsoleMessage - plain data struct constructed from console event params.
5//
6// ConsoleMessage is NOT a ChannelOwner. It is constructed directly from
7// the event params when a "console" event is received.
8//
9// See: <https://playwright.dev/docs/api/class-consolemessage>
10
11/// The source location of a console message.
12///
13/// Contains the URL, line number, and column number of the JavaScript
14/// code that produced the console message.
15///
16/// See: <https://playwright.dev/docs/api/class-consolemessage#console-message-location>
17#[derive(Clone, Debug)]
18#[non_exhaustive]
19pub struct ConsoleMessageLocation {
20    /// The URL of the resource that produced the console message.
21    pub url: String,
22    /// The line number in the resource (1-based).
23    pub line_number: i32,
24    /// The column number in the resource (0-based).
25    pub column_number: i32,
26}
27
28/// Represents a console message emitted by a page.
29///
30/// ConsoleMessage objects are dispatched by the `"console"` event on both
31/// [`Page`](crate::protocol::Page) (via `on_console`) and
32/// [`BrowserContext`](crate::protocol::BrowserContext) (via `on_console`).
33///
34/// See: <https://playwright.dev/docs/api/class-consolemessage>
35#[derive(Clone, Debug)]
36pub struct ConsoleMessage {
37    /// The console message type: "log", "error", "warning", "info", "debug", etc.
38    type_: String,
39    /// The rendered text of the console message.
40    text: String,
41    /// The source location of the console message.
42    location: ConsoleMessageLocation,
43    /// Back-reference to the page that produced this message.
44    page: Option<crate::protocol::Page>,
45    /// The JSHandle arguments passed to the console method.
46    args: Vec<std::sync::Arc<crate::protocol::JSHandle>>,
47    /// The timestamp when the console message was emitted (milliseconds since Unix epoch).
48    timestamp: f64,
49}
50
51impl ConsoleMessage {
52    /// Creates a new `ConsoleMessage` from event params.
53    ///
54    /// This is called by `BrowserContext::on_event("console")` when a console
55    /// event is received from the Playwright server.
56    pub(crate) fn new(
57        type_: String,
58        text: String,
59        location: ConsoleMessageLocation,
60        page: Option<crate::protocol::Page>,
61        args: Vec<std::sync::Arc<crate::protocol::JSHandle>>,
62        timestamp: f64,
63    ) -> Self {
64        Self {
65            type_,
66            text,
67            location,
68            page,
69            args,
70            timestamp,
71        }
72    }
73
74    /// Returns the console message type.
75    ///
76    /// Possible values: `"log"`, `"debug"`, `"info"`, `"error"`, `"warning"`,
77    /// `"dir"`, `"dirxml"`, `"table"`, `"trace"`, `"clear"`, `"startGroup"`,
78    /// `"startGroupCollapsed"`, `"endGroup"`, `"assert"`, `"profile"`,
79    /// `"profileEnd"`, `"count"`, `"timeEnd"`.
80    ///
81    /// See: <https://playwright.dev/docs/api/class-consolemessage#console-message-type>
82    pub fn type_(&self) -> &str {
83        &self.type_
84    }
85
86    /// Returns the text representation of the console message arguments.
87    ///
88    /// See: <https://playwright.dev/docs/api/class-consolemessage#console-message-text>
89    pub fn text(&self) -> &str {
90        &self.text
91    }
92
93    /// Returns the source location of the console message.
94    ///
95    /// See: <https://playwright.dev/docs/api/class-consolemessage#console-message-location>
96    pub fn location(&self) -> &ConsoleMessageLocation {
97        &self.location
98    }
99
100    /// Returns the page that produced the console message, if available.
101    ///
102    /// May be `None` if the page has already been closed or if the message
103    /// originated in a context where the page cannot be resolved.
104    ///
105    /// See: <https://playwright.dev/docs/api/class-consolemessage#console-message-page>
106    pub fn page(&self) -> Option<&crate::protocol::Page> {
107        self.page.as_ref()
108    }
109
110    /// Returns the timestamp when this console message was emitted.
111    ///
112    /// The value is the number of milliseconds since the Unix epoch (January 1, 1970 UTC),
113    /// as a floating-point number. This matches the value sent by the Playwright server
114    /// in the `"console"` event payload.
115    ///
116    /// See: <https://playwright.dev/docs/api/class-consolemessage#console-message-timestamp>
117    pub fn timestamp(&self) -> f64 {
118        self.timestamp
119    }
120
121    /// Returns the list of arguments passed to the console method.
122    ///
123    /// Each argument is a [`JSHandle`](crate::protocol::JSHandle) that can be
124    /// inspected via `json_value()`, `get_property()`, etc.
125    ///
126    /// # Example
127    ///
128    /// ```no_run
129    /// # use playwright_rs::protocol::Playwright;
130    /// # use std::time::Duration;
131    /// # use std::sync::{Arc, Mutex};
132    /// # #[tokio::main]
133    /// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
134    /// let playwright = Playwright::launch().await?;
135    /// let browser = playwright.chromium().launch().await?;
136    /// let page = browser.new_page().await?;
137    ///
138    /// let captured = Arc::new(Mutex::new(None));
139    /// let cap = captured.clone();
140    /// page.on_console(move |msg| {
141    ///     let cap = cap.clone();
142    ///     async move {
143    ///         *cap.lock().unwrap() = Some(msg.args().to_vec());
144    ///         Ok(())
145    ///     }
146    /// }).await?;
147    ///
148    /// page.evaluate_expression("console.log('hello', 42)").await?;
149    /// tokio::time::sleep(Duration::from_millis(200)).await;
150    ///
151    /// let args = captured.lock().unwrap().take().unwrap();
152    /// assert_eq!(args.len(), 2);
153    /// let first = args[0].json_value().await?;
154    /// assert_eq!(first, serde_json::json!("hello"));
155    /// # Ok(())
156    /// # }
157    /// ```
158    ///
159    /// See: <https://playwright.dev/docs/api/class-consolemessage#console-message-args>
160    pub fn args(&self) -> &[std::sync::Arc<crate::protocol::JSHandle>] {
161        &self.args
162    }
163}