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