Skip to content

Commit

Permalink
Allow setting init script through cli
Browse files Browse the repository at this point in the history
  • Loading branch information
Legend-Master committed Nov 21, 2024
1 parent 67c6d70 commit d3bd244
Show file tree
Hide file tree
Showing 4 changed files with 76 additions and 4 deletions.
10 changes: 10 additions & 0 deletions src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,8 @@ pub struct CliArgs {
pub resource_dir: Option<PathBuf>,
/// Override the user agent
pub user_agent: Option<String>,
/// Script to run on document started to load
pub init_script: Option<String>,
/// Initial window's zoom level
pub zoom_level: Option<f32>,
}
Expand Down Expand Up @@ -101,6 +103,12 @@ fn parse_cli_args() -> Result<CliArgs, getopts::Fail> {
"Override the user agent",
"'VersoView/1.0'",
);
opts.optopt(
"",
"init-script",
"Script to run on document started to load",
"console.log('hello world')",
);

opts.optopt(
"w",
Expand Down Expand Up @@ -173,6 +181,7 @@ fn parse_cli_args() -> Result<CliArgs, getopts::Fail> {
};

let user_agent = matches.opt_str("user-agent");
let init_script = matches.opt_str("init-script");

let mut window_attributes = winit::window::Window::default_attributes();

Expand Down Expand Up @@ -237,6 +246,7 @@ fn parse_cli_args() -> Result<CliArgs, getopts::Fail> {
devtools_port,
profiler_settings,
user_agent,
init_script,
zoom_level,
})
}
Expand Down
3 changes: 3 additions & 0 deletions src/verso.rs
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,7 @@ impl Verso {
.clone()
.unwrap_or_else(|| default_user_agent_string().to_string())
.into();
let init_script = config.args.init_script.clone();
let zoom_level = config.args.zoom_level;

config.init();
Expand Down Expand Up @@ -391,6 +392,8 @@ impl Verso {
window.create_webview(&constellation_sender, initial_url.into());
}

window.set_init_script(init_script);

let mut windows = HashMap::new();
windows.insert(window.id(), (window, webrender_document));

Expand Down
58 changes: 54 additions & 4 deletions src/webview.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,9 @@ use crossbeam_channel::Sender;
use embedder_traits::{CompositorEventVariant, EmbedderMsg, PromptDefinition};
use ipc_channel::ipc;
use script_traits::{
webdriver_msg::{WebDriverJSResult, WebDriverScriptCommand},
webdriver_msg::{
WebDriverJSError, WebDriverJSResult, WebDriverJSValue, WebDriverScriptCommand,
},
TraversalDirection, WebDriverCommandMsg,
};
use servo_url::ServoUrl;
Expand All @@ -27,7 +29,7 @@ pub struct WebView {
}

impl WebView {
/// Create a web view from Winit window.
/// Create a web view.
pub fn new(webview_id: WebViewId, rect: DeviceIntRect) -> Self {
Self { webview_id, rect }
}
Expand Down Expand Up @@ -68,8 +70,7 @@ impl Window {
) {
log::trace!("Verso WebView {webview_id:?} is handling Embedder message: {message:?}",);
match message {
EmbedderMsg::LoadStart
| EmbedderMsg::HeadParsed
EmbedderMsg::HeadParsed
| EmbedderMsg::WebViewOpened(_)
| EmbedderMsg::WebViewClosed(_) => {
// Most WebView messages are ignored because it's done by compositor.
Expand All @@ -82,6 +83,11 @@ impl Window {
w
);
}
EmbedderMsg::LoadStart => {
if let Some(init_script) = &self.init_script {
execute_script_async(&sender, &webview_id, init_script);
}
}
EmbedderMsg::LoadComplete => {
self.window.request_redraw();
send_to_constellation(sender, ConstellationMsg::FocusWebView(webview_id));
Expand Down Expand Up @@ -326,3 +332,47 @@ impl Window {
false
}
}

/// Blocking execute a script on this webview
pub fn execute_script(
constellation_sender: &Sender<ConstellationMsg>,
webview: &WebViewId,
js: impl ToString,
) -> Result<WebDriverJSValue, WebDriverJSError> {
let (result_sender, result_receiver) = ipc::channel::<WebDriverJSResult>().unwrap();
send_to_constellation(
constellation_sender,
ConstellationMsg::WebDriverCommand(script_traits::WebDriverCommandMsg::ScriptCommand(
webview.0,
WebDriverScriptCommand::ExecuteScript(js.to_string(), result_sender),
)),
);
result_receiver.recv().unwrap()
}

/// Execute a script asynchronous on this webview
pub fn execute_script_async(
constellation_sender: &Sender<ConstellationMsg>,
webview: &WebViewId,
js: impl ToString,
) {
execute_script_async_with_callback(constellation_sender, webview, js, |_| {})
}

/// Execute a script asynchronous on this webview with a callback processing the result
pub fn execute_script_async_with_callback(
constellation_sender: &Sender<ConstellationMsg>,
webview: &WebViewId,
js: impl ToString,
callback: impl FnOnce(Result<WebDriverJSValue, WebDriverJSError>) + Send + 'static,
) {
let (result_sender, result_receiver) = ipc::channel::<WebDriverJSResult>().unwrap();
send_to_constellation(
constellation_sender,
ConstellationMsg::WebDriverCommand(script_traits::WebDriverCommandMsg::ScriptCommand(
webview.0,
WebDriverScriptCommand::ExecuteAsyncScript(js.to_string(), result_sender),
)),
);
std::thread::spawn(move || callback(result_receiver.recv().unwrap()));
}
9 changes: 9 additions & 0 deletions src/window.rs
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,8 @@ pub struct Window {
pub(crate) panel: Option<Panel>,
/// The WebView of this window.
pub(crate) webview: Option<WebView>,
/// Script to run on document started to load
pub(crate) init_script: Option<String>,
/// The mouse physical position in the web view.
mouse_position: Cell<Option<PhysicalPosition<f64>>>,
/// Modifiers state of the keyboard.
Expand Down Expand Up @@ -118,6 +120,7 @@ impl Window {
surface,
panel: None,
webview: None,
init_script: None,
mouse_position: Default::default(),
modifiers_state: Cell::new(ModifiersState::default()),
history: vec![],
Expand Down Expand Up @@ -162,6 +165,7 @@ impl Window {
surface,
panel: None,
webview: None,
init_script: None,
mouse_position: Default::default(),
modifiers_state: Cell::new(ModifiersState::default()),
history: vec![],
Expand Down Expand Up @@ -232,6 +236,11 @@ impl Window {
log::debug!("Verso Window {:?} adds webview {}", self.id(), webview_id);
}

/// Set the init script that runs on document started to load.
pub fn set_init_script(&mut self, init_script: Option<String>) {
self.init_script = init_script;
}

/// Handle Winit window event and return a boolean to indicate if the compositor should repaint immediately.
pub fn handle_winit_window_event(
&mut self,
Expand Down

0 comments on commit d3bd244

Please sign in to comment.