use tracing::{info, instrument};
use super::Page;
use crate::error::PageError;
impl Page {
#[instrument(level = "info", skip(self, script), fields(script_len = script.as_ref().len()))]
pub async fn add_init_script(&self, script: impl AsRef<str>) -> Result<String, PageError> {
if self.is_closed() {
return Err(PageError::Closed);
}
use viewpoint_cdp::protocol::page::AddScriptToEvaluateOnNewDocumentParams;
let result: viewpoint_cdp::protocol::page::AddScriptToEvaluateOnNewDocumentResult = self
.connection()
.send_command(
"Page.addScriptToEvaluateOnNewDocument",
Some(AddScriptToEvaluateOnNewDocumentParams {
source: script.as_ref().to_string(),
world_name: None,
include_command_line_api: None,
run_immediately: None,
}),
Some(self.session_id()),
)
.await?;
info!(identifier = %result.identifier, "Init script added");
Ok(result.identifier)
}
#[instrument(level = "info", skip(self), fields(path = %path.as_ref().display()))]
pub async fn add_init_script_path(
&self,
path: impl AsRef<std::path::Path>,
) -> Result<String, PageError> {
let content = tokio::fs::read_to_string(path.as_ref())
.await
.map_err(|e| {
PageError::EvaluationFailed(format!("Failed to read init script file: {e}"))
})?;
self.add_init_script(&content).await
}
}