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}
47
48impl ConsoleMessage {
49    /// Creates a new `ConsoleMessage` from event params.
50    ///
51    /// This is called by `BrowserContext::on_event("console")` when a console
52    /// event is received from the Playwright server.
53    pub(crate) fn new(
54        type_: String,
55        text: String,
56        location: ConsoleMessageLocation,
57        page: Option<crate::protocol::Page>,
58        args: Vec<std::sync::Arc<crate::protocol::JSHandle>>,
59    ) -> Self {
60        Self {
61            type_,
62            text,
63            location,
64            page,
65            args,
66        }
67    }
68
69    /// Returns the console message type.
70    ///
71    /// Possible values: `"log"`, `"debug"`, `"info"`, `"error"`, `"warning"`,
72    /// `"dir"`, `"dirxml"`, `"table"`, `"trace"`, `"clear"`, `"startGroup"`,
73    /// `"startGroupCollapsed"`, `"endGroup"`, `"assert"`, `"profile"`,
74    /// `"profileEnd"`, `"count"`, `"timeEnd"`.
75    ///
76    /// See: <https://playwright.dev/docs/api/class-consolemessage#console-message-type>
77    pub fn type_(&self) -> &str {
78        &self.type_
79    }
80
81    /// Returns the text representation of the console message arguments.
82    ///
83    /// See: <https://playwright.dev/docs/api/class-consolemessage#console-message-text>
84    pub fn text(&self) -> &str {
85        &self.text
86    }
87
88    /// Returns the source location of the console message.
89    ///
90    /// See: <https://playwright.dev/docs/api/class-consolemessage#console-message-location>
91    pub fn location(&self) -> &ConsoleMessageLocation {
92        &self.location
93    }
94
95    /// Returns the page that produced the console message, if available.
96    ///
97    /// May be `None` if the page has already been closed or if the message
98    /// originated in a context where the page cannot be resolved.
99    ///
100    /// See: <https://playwright.dev/docs/api/class-consolemessage#console-message-page>
101    pub fn page(&self) -> Option<&crate::protocol::Page> {
102        self.page.as_ref()
103    }
104
105    /// Returns the list of arguments passed to the console method.
106    ///
107    /// Each argument is a [`JSHandle`](crate::protocol::JSHandle) that can be
108    /// inspected via `json_value()`, `get_property()`, etc.
109    ///
110    /// # Example
111    ///
112    /// ```ignore
113    /// # use playwright_rs::protocol::Playwright;
114    /// # use std::time::Duration;
115    /// # use std::sync::{Arc, Mutex};
116    /// # #[tokio::main]
117    /// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
118    /// let playwright = Playwright::launch().await?;
119    /// let browser = playwright.chromium().launch().await?;
120    /// let page = browser.new_page().await?;
121    ///
122    /// let captured = Arc::new(Mutex::new(None));
123    /// let cap = captured.clone();
124    /// page.on_console(move |msg| {
125    ///     let cap = cap.clone();
126    ///     async move {
127    ///         *cap.lock().unwrap() = Some(msg.args().to_vec());
128    ///         Ok(())
129    ///     }
130    /// }).await?;
131    ///
132    /// page.evaluate_expression("console.log('hello', 42)").await?;
133    /// tokio::time::sleep(Duration::from_millis(200)).await;
134    ///
135    /// let args = captured.lock().unwrap().take().unwrap();
136    /// assert_eq!(args.len(), 2);
137    /// let first = args[0].json_value().await?;
138    /// assert_eq!(first, serde_json::json!("hello"));
139    /// # Ok(())
140    /// # }
141    /// ```
142    ///
143    /// See: <https://playwright.dev/docs/api/class-consolemessage#console-message-args>
144    pub fn args(&self) -> &[std::sync::Arc<crate::protocol::JSHandle>] {
145        &self.args
146    }
147}