use std::time::Duration;
use drission::prelude::*;
#[tokio::main]
async fn main() -> drission::Result<()> {
tracing_subscriber::fmt()
.with_env_filter(
tracing_subscriber::EnvFilter::try_from_default_env().unwrap_or_else(|_| "warn".into()),
)
.init();
let browser = Browser::launch(
BrowserOptions::new()
.headless(true)
.bypass_csp(true)
.ignore_https_errors(true),
)
.await?;
let tab = browser.latest_tab().await?;
tab.get("https://example.com/").await?;
tab.intercept_xhr(&["/api/"]).await?;
tab.run_js(
"window.__hijacked = null; \
fetch('https://example.com/api/profile') \
.then(r => r.json()).then(j => window.__hijacked = j) \
.catch(e => window.__hijacked = { error: String(e) }); true",
)
.await?;
let req = tab.intercept_next().await?;
println!("拦截到: {} {} [{}]", req.method, req.url, req.resource_type);
req.fulfill(
200,
vec![("content-type".to_string(), "application/json".to_string())],
r#"{"id":1,"name":"drission","hijacked":true}"#,
)
.await?;
let mut got = serde_json::Value::Null;
for _ in 0..30 {
let v = tab.run_js("window.__hijacked").await?;
if !v.is_null() {
got = v;
break;
}
tokio::time::sleep(Duration::from_millis(100)).await;
}
println!("页面 JS 实际拿到的响应(已被伪造): {got}");
tab.intercept_stop().await?;
browser.quit().await?;
println!("完成。");
Ok(())
}