chromedriver_api/session/
tab.rs1use crate::{ prelude::*, TaskManager };
2
3use reqwest::Client;
4use serde_json::{ json, Value };
5
6#[derive(Debug)]
8pub struct Tab {
9 pub(crate) client: Client,
10 pub(crate) port: String,
11 pub(crate) session_id: String,
12 pub(crate) window_handle: String,
13 pub(crate) url: String,
14 pub(crate) manager: Arc<TaskManager>
15}
16
17impl Tab {
18 async fn active_without_lock(&mut self) -> Result<()> {
20 self.client
21 .post(&format!("http://localhost:{}/session/{}/window", self.port, self.session_id))
22 .json(&json!({"handle": self.window_handle }))
23 .send()
24 .await?
25 .error_for_status()?;
26
27 Ok(())
28 }
29
30 pub async fn active(&mut self) -> Result<()> {
32 self.manager.lock().await;
34
35 self.active_without_lock().await?;
36
37 self.manager.unlock().await;
39
40 Ok(())
41 }
42
43 pub async fn open<S>(&mut self, url: S) -> Result<()>
45 where
46 S: Into<String>
47 {
48 let url = url.into();
49
50 self.manager.lock().await;
52
53 self.active_without_lock().await?;
55
56 self.client
58 .post(&format!("http://localhost:{}/session/{}/url", self.port, self.session_id))
59 .json(&json!({ "url": url }))
60 .send()
61 .await?
62 .error_for_status()?;
63
64 self.url = url.into();
65
66 self.manager.unlock().await;
68
69 Ok(())
70 }
71
72 pub async fn inject(&mut self, script: &str) -> Result<Value> {
74 self.manager.lock().await;
76
77 self.active_without_lock().await?;
79
80 let url = format!("http://localhost:{}/session/{}/execute/sync", self.port, self.session_id);
82 let response = self.client
83 .post(&url)
84 .json(&json!({
85 "script": script,
86 "args": []
87 }))
88 .send()
89 .await?
90 .error_for_status()?
91 .json::<Value>()
92 .await?;
93
94 self.manager.unlock().await;
96
97 Ok(response["value"].clone())
98 }
99
100 pub async fn close(&mut self) -> Result<()> {
102 self.manager.lock().await;
104
105 self.active_without_lock().await?;
107
108 self.client
110 .delete(&format!("http://localhost:{}/session/{}/window", self.port, self.session_id))
111 .send()
112 .await?
113 .error_for_status()?;
114
115 self.manager.unlock().await;
117
118 Ok(())
119 }
120}