1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
use std::sync::Arc;
use serde_json::json;
use anyhow::{Context, Result};
use crate::general_utils;
use crate::element::Element;
use crate::transport::Transport;
use crate::general_utils::next_id;
use crate::transport_actor::TransportResponse;
/// A tab instance.
pub struct Tab {
pub(crate) transport: Arc<Transport>,
pub(crate) session_id: String,
pub(crate) target_id: String,
}
impl Tab {
/**
Create a new tab instance.
# Example
```no_run
use cdp_html_shot::Browser;
use anyhow::Result;
#[tokio::main]
async fn main() -> Result<()> {
let browser = Browser::new().await?;
let tab = browser.new_tab().await?;
Ok(())
}
```
*/
pub(crate) async fn new(transport: Arc<Transport>) -> Result<Self> {
let TransportResponse::Response(res) = transport.send(json!({
"id": next_id(),
"method": "Target.createTarget",
"params": {
"url": "about:blank"
}
})).await? else { panic!() };
let target_id = res
.result
.get("targetId")
.context("Failed to get targetId")?
.as_str()
.unwrap();
let TransportResponse::Response(res) = transport.send(json!({
"id": next_id(),
"method": "Target.attachToTarget",
"params": {
"targetId": target_id
}
})).await? else { panic!() };
let session_id = res
.result["sessionId"]
.as_str()
.unwrap();
Ok(Self {
transport,
session_id: String::from(session_id),
target_id: String::from(target_id),
})
}
/**
Set the content of the tab.
# Example
```no_run
use cdp_html_shot::Browser;
use anyhow::Result;
#[tokio::main]
async fn main() -> Result<()> {
let browser = Browser::new().await?;
let tab = browser.new_tab().await?;
tab.set_content("<h1>Hello world!</h1>").await?;
Ok(())
}
```
*/
pub async fn set_content(&self, content: &str) -> Result<&Self> {
let content = match (content.contains('`'), content.contains("${")) {
(true, true) => &content.replace('`', "${BACKTICK}").replace("${", "$ {"),
(true, false) => &content.replace('`', "${BACKTICK}"),
(false, true) => &content.replace("${", "$ {"),
(false, false) => content,
};
let expression = format!(
r#"
(async () => {{
try {{
const BACKTICK = '`';
document.open();
document.write(String.raw`{content}`);
document.close();
await Promise.race([
new Promise((resolve) => {{
const checkResources = async () => {{
if (document.readyState !== 'complete') {{
return false;
}}
const images = Array.from(document.images);
const imagePromises = images.map(img => {{
if (img.complete) return Promise.resolve();
return new Promise(resolve => {{
img.onload = resolve;
img.onerror = resolve;
}});
}});
const styleSheets = Array.from(document.styleSheets);
const stylePromises = styleSheets.map(sheet => {{
if (!sheet.href) return Promise.resolve();
return new Promise(resolve => {{
const link = document.querySelector(`link[href="${{sheet.href}}"]`);
if (link.sheet) resolve();
else {{
link.onload = resolve;
link.onerror = resolve;
}}
}});
}});
await Promise.all([...imagePromises, ...stylePromises]);
return new Promise(resolve => {{
requestAnimationFrame(() => {{
requestAnimationFrame(resolve);
}});
}});
}};
checkResources().then(resolved => {{
if (!resolved) {{
window.addEventListener('load', () => {{
checkResources().then(resolve);
}});
}} else {{
resolve(true);
}}
}});
}}),
new Promise((_, reject) => {{
setTimeout(() => reject(new Error('Timeout')), 30000);
}})
]);
return 'Page loaded successfully';
}} catch (error) {{
throw new Error(`Failed to set content: ${{error.message}}`);
}}
}})();
"#
);
let msg_id = next_id();
let msg = json!({
"id": msg_id,
"method": "Runtime.evaluate",
"params": {
"expression": expression,
"awaitPromise": true,
}
}).to_string();
general_utils::send_and_get_msg(self.transport.clone(), msg_id, &self.session_id, msg).await?;
Ok(self)
}
/**
Find an element by CSS selector.
# Example
```no_run
use cdp_html_shot::Browser;
use anyhow::Result;
#[tokio::main]
async fn main() -> Result<()> {
let browser = Browser::new().await?;
let tab = browser.new_tab().await?;
let element = tab.find_element("h1").await?;
Ok(())
}
```
*/
pub async fn find_element(&self, selector: &str) -> Result<Element> {
let msg_id = next_id();
let msg = json!({
"id": msg_id,
"method": "DOM.getDocument",
"params": {}
}).to_string();
let res = general_utils::send_and_get_msg(self.transport.clone(), msg_id, &self.session_id, msg).await?;
let msg = general_utils::serde_msg(&res);
let node_id = msg["result"]["root"]["nodeId"]
.as_u64()
.unwrap();
let msg_id = next_id();
let msg = json!({
"id": msg_id,
"method": "DOM.querySelector",
"params": {
"nodeId": node_id,
"selector": selector
}
}).to_string();
let res = general_utils::send_and_get_msg(self.transport.clone(), msg_id, &self.session_id, msg).await?;
let msg = general_utils::serde_msg(&res);
let node_id = match msg["result"]["nodeId"].as_u64() {
Some(node_id) => node_id,
None => return Err(anyhow::anyhow!("Element not found")),
};
Element::new(self, node_id).await
}
/**
Close the tab.
# Example
```no_run
use cdp_html_shot::Browser;
use anyhow::Result;
#[tokio::main]
async fn main() -> Result<()> {
let browser = Browser::new().await?;
let tab = browser.new_tab().await?;
tab.close().await?;
Ok(())
}
```
*/
pub async fn activate(&self) -> Result<&Self> {
let msg_id = next_id();
let msg = json!({
"id": msg_id,
"method": "Target.activateTarget",
"params": {
"targetId": self.target_id
}
}).to_string();
general_utils::send_and_get_msg(self.transport.clone(), msg_id, &self.session_id, msg).await?;
Ok(self)
}
/**
Navigate to a URL.
# Warning
This API does not wait for the page to load, it is only used to navigate to local HTML files,
which is convenient for getting font and other resources.
# Example
```no_run
use cdp_html_shot::Browser;
use anyhow::Result;
use tokio::time;
#[tokio::main]
async fn main() -> Result<()> {
let browser = Browser::new().await?;
let tab = browser.new_tab().await?;
tab.goto("https://www.rust-lang.org/").await?;
time::sleep(time::Duration::from_secs(5)).await;
Ok(())
}
```
*/
pub async fn goto(&self, url: &str) -> Result<&Self> {
let msg_id = next_id();
let msg = json!({
"id": msg_id,
"method": "Page.navigate",
"params": {
"url": url
}
}).to_string();
general_utils::send_and_get_msg(self.transport.clone(), msg_id, &self.session_id, msg).await?;
Ok(self)
}
/**
Close the tab.
# Example
```no_run
use cdp_html_shot::Browser;
use anyhow::Result;
#[tokio::main]
async fn main() -> Result<()> {
let browser = Browser::new().await?;
let tab = browser.new_tab().await?;
tab.close().await?;
Ok(())
}
```
*/
pub async fn close(&self) -> Result<()> {
let msg_id = next_id();
let msg = json!({
"id": msg_id,
"method": "Target.closeTarget",
"params": {
"targetId": self.target_id
}
}).to_string();
general_utils::send_and_get_msg(self.transport.clone(), msg_id, &self.session_id, msg).await?;
Ok(())
}
}