Skip to content

armgit / moli

Public Imported from GitHub
0

Best headless browser for AI agents. Lite, Fast, High-Compatibility. Built in Rust

fix(navigation): honor input disposition for popup activation

ldm05b9a21bc2592
diff --git a/moli-core/src/page/mod.rs b/moli-core/src/page/mod.rs
index abff4dd80..f11943d51 100644
--- a/moli-core/src/page/mod.rs
+++ b/moli-core/src/page/mod.rs
@@ -113,7 +113,7 @@ pub use moli_renderer_v8::{
RendererPendingJavaScriptDialog, RendererPendingPopupActivation,
RendererPendingSameDocumentNavigation, RendererPendingTopLevelHistoryTraversal,
RendererPendingWindowOpenEvent, RendererPerformanceMetricSnapshot,
- RendererPointerEventProperties, RendererPopupActivationSource,
+ RendererPointerEventProperties, RendererPopupActivationSource, RendererPopupDisposition,
RendererResourceTextSearchOutcome, RendererRuntimeCommandOutput, RendererRuntimeHeapUsage,
RendererRuntimeInspectorIoCommandClaim, RendererRuntimeInspectorIoCommandRoute,
RendererRuntimeInspectorMainCommandCompletion, RendererRuntimeInspectorMainCommandRoute,
diff --git a/moli-protocol-server/src/cdp_scheduler.rs b/moli-protocol-server/src/cdp_scheduler.rs
index 56ba8e1b5..f37c083d9 100644
--- a/moli-protocol-server/src/cdp_scheduler.rs
+++ b/moli-protocol-server/src/cdp_scheduler.rs
@@ -1818,8 +1818,8 @@ impl CdpScheduler {
let blocked_by_prior_residence = target_ids
.iter()
.any(|target_id| blocked_target_ids.contains(target_id));
- let blocked_by_navigation =
- self.protocol_targets_have_inflight_background_navigation(&target_ids);
+ let blocked_by_navigation = !residence.bypasses_inflight_navigation_gate()
+ && self.protocol_targets_have_inflight_background_navigation(&target_ids);
if blocked_by_prior_residence || blocked_by_navigation {
if target_ids.is_empty() {
retained.push_back(residence);
@@ -1892,7 +1892,9 @@ impl CdpScheduler {
{
continue;
}
- if self.protocol_targets_have_inflight_background_navigation(&target_ids) {
+ if !residence.bypasses_inflight_navigation_gate()
+ && self.protocol_targets_have_inflight_background_navigation(&target_ids)
+ {
if target_ids.is_empty() {
return None;
}
diff --git a/moli-protocol-server/src/cdp_scheduler/protocol_residence.rs b/moli-protocol-server/src/cdp_scheduler/protocol_residence.rs
index 0849ebc67..19d00a3bc 100644
--- a/moli-protocol-server/src/cdp_scheduler/protocol_residence.rs
+++ b/moli-protocol-server/src/cdp_scheduler/protocol_residence.rs
@@ -108,6 +108,13 @@ pub(super) enum ClientTurnPredecessor {
}
impl ProtocolSchedulerResidence {
+ pub(super) fn bypasses_inflight_navigation_gate(&self) -> bool {
+ matches!(
+ self,
+ Self::ProtocolWork { work, .. } if work.bypasses_inflight_navigation_gate()
+ )
+ }
+
pub(super) fn should_yield_to_client_turn(&self) -> bool {
matches!(
self,
diff --git a/moli-protocol/src/conn.rs b/moli-protocol/src/conn.rs
index 9bdbcbe13..d7dd0fac7 100644
--- a/moli-protocol/src/conn.rs
+++ b/moli-protocol/src/conn.rs
@@ -45,6 +45,7 @@ mod fetch_support;
mod inspector_route;
mod output;
mod page_state;
+mod popup_activation_work;
mod popup_navigation_work;
mod protocol_output;
mod renderer_command_turn;
@@ -499,6 +500,7 @@ pub(crate) use output::{
build_command_success_response,
};
pub(crate) use page_state::{LoadedNavigationPageCommit, LoadedNavigationRendererAttachmentCommit};
+pub(crate) use popup_activation_work::PopupTargetActivationAction;
pub(crate) use popup_navigation_work::{
PopupTargetNavigationKind, PopupTargetNavigationOwnerAction,
};
@@ -2735,6 +2737,21 @@ impl CdpConnection {
.push_scheduler_event(CdpSchedulerEvent::ProtocolWorkPublished { work });
}
+ pub(crate) fn publish_popup_target_activation_action(
+ &mut self,
+ action: PopupTargetActivationAction,
+ ) {
+ let publish_sequence = self
+ .scheduler_state
+ .allocate_protocol_work_publish_sequence();
+ let work = crate::domains::activity::ProtocolSchedulerWork::popup_target_activation_action(
+ publish_sequence,
+ action,
+ );
+ self.scheduler_state
+ .push_scheduler_event(CdpSchedulerEvent::ProtocolWorkPublished { work });
+ }
+
pub(crate) fn publish_page_target_termination_owner_action(
&mut self,
action: crate::domains::page::PageTargetTerminationOwnerAction,
diff --git a/moli-protocol/src/conn/popup_activation_work.rs b/moli-protocol/src/conn/popup_activation_work.rs
new file mode 100644
index 000000000..09382ff89
--- /dev/null
+++ b/moli-protocol/src/conn/popup_activation_work.rs
@@ -0,0 +1,48 @@
+use super::{CdpConnection, CdpSessionRoute, CommandOwnerScope};
+
+/// Foreground activation for one already-created auxiliary target.
+///
+/// Target creation and navigation have separate lifetimes. In particular, a
+/// target waiting for `Runtime.runIfWaitingForDebugger` must still become the
+/// selected target immediately. This move-only action freezes the exact
+/// target identity while allowing that target to move between background and
+/// active residence before the action completes.
+#[derive(Debug)]
+pub(crate) struct PopupTargetActivationAction {
+ owner_scope: CommandOwnerScope,
+ browser_context_id: String,
+ target_id: String,
+}
+
+impl PopupTargetActivationAction {
+ pub(crate) fn capture(
+ conn: &CdpConnection,
+ browser_context_id: &str,
+ target_id: &str,
+ ) -> Option<Self> {
+ let route = conn.target_session_route_for_target_id(target_id)?;
+ (route.browser_context_id() == Some(browser_context_id)).then(|| Self {
+ owner_scope: CommandOwnerScope::from_session_and_owner_route(
+ None,
+ Some(CdpSessionRoute::AuxiliaryTarget {
+ browser_context_id: browser_context_id.to_owned(),
+ target_id: target_id.to_owned(),
+ }),
+ ),
+ browser_context_id: browser_context_id.to_owned(),
+ target_id: target_id.to_owned(),
+ })
+ }
+
+ pub(crate) fn browser_context_id(&self) -> &str {
+ &self.browser_context_id
+ }
+
+ pub(crate) fn target_id(&self) -> &str {
+ &self.target_id
+ }
+
+ pub(crate) fn into_parts(self) -> (CommandOwnerScope, String, String) {
+ (self.owner_scope, self.browser_context_id, self.target_id)
+ }
+}
diff --git a/moli-protocol/src/conn/popup_navigation_work.rs b/moli-protocol/src/conn/popup_navigation_work.rs
index 35c043ed5..0f6fe283a 100644
--- a/moli-protocol/src/conn/popup_navigation_work.rs
+++ b/moli-protocol/src/conn/popup_navigation_work.rs
@@ -1,4 +1,4 @@
-use super::{CdpConnection, CommandOwnerScope};
+use super::{CdpConnection, CdpSessionRoute, CommandOwnerScope};
/// Navigation requested by an already-accepted auxiliary browsing-context
/// action.
@@ -37,7 +37,16 @@ impl PopupTargetNavigationOwnerAction {
) -> Option<Self> {
let route = conn.target_session_route_for_target_id(target_id)?;
(route.browser_context_id() == Some(browser_context_id)).then(|| Self {
- owner_scope: CommandOwnerScope::from_session_and_owner_route(None, Some(route)),
+ // Activation has an independent owner action. Unlike a frozen
+ // BackgroundTarget route, AuxiliaryTarget keeps this exact target
+ // addressable if that action changes its residence first.
+ owner_scope: CommandOwnerScope::from_session_and_owner_route(
+ None,
+ Some(CdpSessionRoute::AuxiliaryTarget {
+ browser_context_id: browser_context_id.to_owned(),
+ target_id: target_id.to_owned(),
+ }),
+ ),
browser_context_id: browser_context_id.to_owned(),
target_id: target_id.to_owned(),
url,
diff --git a/moli-protocol/src/conn/protocol_output.rs b/moli-protocol/src/conn/protocol_output.rs
index f289c8c95..83ad78797 100644
--- a/moli-protocol/src/conn/protocol_output.rs
+++ b/moli-protocol/src/conn/protocol_output.rs
@@ -209,6 +209,10 @@ impl CdpConnection {
)
.await
}
+ ReadyProtocolSchedulerWork::PopupTargetActivationAction(action) => {
+ crate::domains::target::complete_popup_target_activation_action_async(self, action)
+ .await
+ }
ReadyProtocolSchedulerWork::PageTargetTerminationOwnerAction(action) => {
crate::domains::page::complete_page_target_termination_owner_action_async(
self, action,
diff --git a/moli-protocol/src/domains/activity/scheduler_work.rs b/moli-protocol/src/domains/activity/scheduler_work.rs
index 83f5aaec1..60184f204 100644
--- a/moli-protocol/src/domains/activity/scheduler_work.rs
+++ b/moli-protocol/src/domains/activity/scheduler_work.rs
@@ -6,8 +6,8 @@ use crate::{
conn::{
BidiChannelOwnerAction, CdpConnection, DeferredMainDocumentLoadCompletionOutputAction,
DeferredMainDocumentLoadCompletionOutputInterest,
- PendingDeferredMainDocumentLoadCompletion, PopupTargetNavigationOwnerAction,
- TopLevelLocationNavigationOwnerAction,
+ PendingDeferredMainDocumentLoadCompletion, PopupTargetActivationAction,
+ PopupTargetNavigationOwnerAction, TopLevelLocationNavigationOwnerAction,
},
devtools_runtime::DevToolsCommandContext,
};
@@ -49,6 +49,7 @@ pub enum ProtocolSchedulerWorkKind {
BidiChannelOwnerAction,
TopLevelLocationNavigationOwnerAction,
PopupTargetNavigationOwnerAction,
+ PopupTargetActivationAction,
PageTargetTerminationOwnerAction,
}
@@ -71,6 +72,7 @@ enum ProtocolSchedulerWorkPayload {
BidiChannelOwnerAction(BidiChannelOwnerAction),
TopLevelLocationNavigationOwnerAction(TopLevelLocationNavigationOwnerAction),
PopupTargetNavigationOwnerAction(PopupTargetNavigationOwnerAction),
+ PopupTargetActivationAction(PopupTargetActivationAction),
PageTargetTerminationOwnerAction(crate::domains::page::PageTargetTerminationOwnerAction),
}
@@ -116,6 +118,11 @@ impl fmt::Debug for ProtocolSchedulerWork {
.field("url", &action.url())
.field("navigation_kind", &action.kind());
}
+ ProtocolSchedulerWorkPayload::PopupTargetActivationAction(action) => {
+ debug
+ .field("browser_context_id", &action.browser_context_id())
+ .field("target_id", &action.target_id());
+ }
ProtocolSchedulerWorkPayload::PageTargetTerminationOwnerAction(action) => {
debug
.field("action", &action.kind())
@@ -180,6 +187,16 @@ impl ProtocolSchedulerWork {
}
}
+ pub(crate) fn popup_target_activation_action(
+ publish_sequence: ProtocolWorkPublishSequence,
+ action: PopupTargetActivationAction,
+ ) -> Self {
+ Self {
+ publish_sequence,
+ payload: ProtocolSchedulerWorkPayload::PopupTargetActivationAction(action),
+ }
+ }
+
pub(crate) fn page_target_termination_owner_action(
publish_sequence: ProtocolWorkPublishSequence,
action: crate::domains::page::PageTargetTerminationOwnerAction,
@@ -211,6 +228,9 @@ impl ProtocolSchedulerWork {
ProtocolSchedulerWorkPayload::PopupTargetNavigationOwnerAction(_) => {
ProtocolSchedulerWorkKind::PopupTargetNavigationOwnerAction
}
+ ProtocolSchedulerWorkPayload::PopupTargetActivationAction(_) => {
+ ProtocolSchedulerWorkKind::PopupTargetActivationAction
+ }
ProtocolSchedulerWorkPayload::PageTargetTerminationOwnerAction(_) => {
ProtocolSchedulerWorkKind::PageTargetTerminationOwnerAction
}
@@ -232,10 +252,20 @@ impl ProtocolSchedulerWork {
ProtocolSchedulerWorkPayload::BidiChannelOwnerAction(_) => true,
ProtocolSchedulerWorkPayload::TopLevelLocationNavigationOwnerAction(_) => true,
ProtocolSchedulerWorkPayload::PopupTargetNavigationOwnerAction(_) => true,
+ ProtocolSchedulerWorkPayload::PopupTargetActivationAction(_) => true,
ProtocolSchedulerWorkPayload::PageTargetTerminationOwnerAction(_) => true,
}
}
+ /// Reports owner work that must complete inside the producing command's
+ /// turn.
+ ///
+ /// Popup navigation is safe to start while completing the producing
+ /// command: it retains its exact target route and cannot replace the
+ /// command's active renderer. Popup activation is deliberately excluded.
+ /// It can replace that renderer and must therefore cross the ordinary
+ /// client-turn predecessor so the opener's command result is collected
+ /// from its original owner first.
pub fn is_command_followup(&self) -> bool {
matches!(
&self.payload,
@@ -263,12 +293,30 @@ impl ProtocolSchedulerWork {
ProtocolSchedulerWorkPayload::PopupTargetNavigationOwnerAction(action) => {
Some(action.target_id())
}
+ ProtocolSchedulerWorkPayload::PopupTargetActivationAction(action) => {
+ Some(action.target_id())
+ }
ProtocolSchedulerWorkPayload::PageTargetTerminationOwnerAction(action) => {
Some(action.target_id())
}
}
}
+ /// Reports work whose transition is independent of an in-flight document
+ /// load on the same target.
+ ///
+ /// Foreground selection happens when Chromium accepts a user activation,
+ /// not when the selected target finishes loading. This also lets a target
+ /// paused by `waitForDebuggerOnStart` become active before its initial
+ /// navigation is released. The exact target id above still preserves
+ /// target-local ordering against earlier scheduler residences.
+ pub fn bypasses_inflight_navigation_gate(&self) -> bool {
+ matches!(
+ &self.payload,
+ ProtocolSchedulerWorkPayload::PopupTargetActivationAction(_)
+ )
+ }
+
pub fn is_top_level_location_navigation_owner_action(&self) -> bool {
matches!(
&self.payload,
@@ -371,6 +419,7 @@ impl ProtocolSchedulerWork {
| ProtocolSchedulerWorkPayload::BidiChannelOwnerAction(_)
| ProtocolSchedulerWorkPayload::TopLevelLocationNavigationOwnerAction(_)
| ProtocolSchedulerWorkPayload::PopupTargetNavigationOwnerAction(_)
+ | ProtocolSchedulerWorkPayload::PopupTargetActivationAction(_)
| ProtocolSchedulerWorkPayload::PageTargetTerminationOwnerAction(_) => {
panic!("only main-document load owner work can start a lifecycle wait")
}
@@ -424,6 +473,7 @@ pub(crate) enum ReadyProtocolSchedulerWork {
BidiChannelOwnerAction(BidiChannelOwnerAction),
TopLevelLocationNavigationOwnerAction(TopLevelLocationNavigationOwnerAction),
PopupTargetNavigationOwnerAction(PopupTargetNavigationOwnerAction),
+ PopupTargetActivationAction(PopupTargetActivationAction),
PageTargetTerminationOwnerAction(crate::domains::page::PageTargetTerminationOwnerAction),
}
@@ -450,6 +500,9 @@ impl ProtocolSchedulerWork {
ProtocolSchedulerWorkPayload::PopupTargetNavigationOwnerAction(action) => {
ReadyProtocolSchedulerWork::PopupTargetNavigationOwnerAction(action)
}
+ ProtocolSchedulerWorkPayload::PopupTargetActivationAction(action) => {
+ ReadyProtocolSchedulerWork::PopupTargetActivationAction(action)
+ }
ProtocolSchedulerWorkPayload::PageTargetTerminationOwnerAction(action) => {
ReadyProtocolSchedulerWork::PageTargetTerminationOwnerAction(action)
}
diff --git a/moli-protocol/src/domains/page.rs b/moli-protocol/src/domains/page.rs
index 36ee5adcd..2ba093d34 100644
--- a/moli-protocol/src/domains/page.rs
+++ b/moli-protocol/src/domains/page.rs
@@ -2467,7 +2467,7 @@ mod producer_tests {
RendererPageCreationArtifacts, RendererPendingDownloadActivation,
RendererPendingFileChooserActivation, RendererPendingJavaScriptDialog,
RendererPendingPopupActivation, RendererPendingSameDocumentNavigation,
- RendererWindowDocumentSource, SubresourceResponseBody,
+ RendererPopupDisposition, RendererWindowDocumentSource, SubresourceResponseBody,
};
use serde_json::{Value, json};
@@ -2973,6 +2973,7 @@ mod producer_tests {
Some(POPUP_ID),
"about:blank".to_owned(),
"_blank".to_owned(),
+ RendererPopupDisposition::Background,
)],
),
));
@@ -3041,6 +3042,7 @@ mod producer_tests {
Some(POPUP_ID),
"about:blank".to_owned(),
"_blank".to_owned(),
+ RendererPopupDisposition::Background,
)],
),
)
@@ -3196,6 +3198,7 @@ mod producer_tests {
Some(POPUP_ID),
"about:blank".to_owned(),
"_blank".to_owned(),
+ RendererPopupDisposition::Background,
)],
),
)
@@ -3515,6 +3518,7 @@ mod producer_tests {
None,
"data:text/html,%3Cmain%3Eordered-popup%3C/main%3E".to_owned(),
"_blank".to_owned(),
+ RendererPopupDisposition::Background,
)],
),
)
@@ -4736,6 +4740,7 @@ mod producer_tests {
None,
"data:text/html,%3Cmain%3Eprepared-popup%3C/main%3E".to_owned(),
"_blank".to_owned(),
+ RendererPopupDisposition::Background,
)],
),
));
@@ -4819,6 +4824,7 @@ mod producer_tests {
None,
"data:text/html,%3Cmain%3Eautomation-popup%3C/main%3E".to_owned(),
"_blank".to_owned(),
+ RendererPopupDisposition::Background,
)],
),
));
@@ -4865,6 +4871,7 @@ mod producer_tests {
None,
"https://example.test/self".to_owned(),
"_self".to_owned(),
+ RendererPopupDisposition::Background,
);
}
diff --git a/moli-protocol/src/domains/page/popup.rs b/moli-protocol/src/domains/page/popup.rs
index d8eb781a9..2db7b80e7 100644
--- a/moli-protocol/src/domains/page/popup.rs
+++ b/moli-protocol/src/domains/page/popup.rs
@@ -89,6 +89,7 @@ pub(super) async fn emit_prepared(
} = prepared;
let (
source,
+ disposition,
popup_id,
url,
target_name,
@@ -110,6 +111,7 @@ pub(super) async fn emit_prepared(
target_name,
opener,
can_access_opener,
+ disposition,
session_storage_store,
initial_empty_document_storage_key,
);
@@ -198,7 +200,7 @@ mod tests {
PageId,
page::{
RendererDocumentLifecycleIdentity, RendererDocumentToken, RendererFrameToken,
- RendererLifecycleEpoch,
+ RendererLifecycleEpoch, RendererPopupDisposition,
},
};
@@ -243,6 +245,7 @@ mod tests {
popup_id,
url.to_owned(),
"_blank".to_owned(),
+ RendererPopupDisposition::Background,
)
}
@@ -457,6 +460,7 @@ mod tests {
Some(46),
"about:blank#removed-context".to_owned(),
"_blank".to_owned(),
+ RendererPopupDisposition::Background,
)],
)
.await;
diff --git a/moli-protocol/src/domains/target.rs b/moli-protocol/src/domains/target.rs
index b94ed5b6f..0dfecb2d9 100644
--- a/moli-protocol/src/domains/target.rs
+++ b/moli-protocol/src/domains/target.rs
@@ -22,7 +22,7 @@ mod worker_target;
pub(in crate::domains) use browser_context::devtools_client_window_info_for_target;
pub(crate) use lifecycle::{
- PopupTargetCreation, PopupTargetOpenerIdentity,
+ PopupTargetCreation, PopupTargetOpenerIdentity, complete_popup_target_activation_action_async,
complete_popup_target_navigation_owner_action_async,
create_popup_target_from_renderer_output_background_events_async,
emit_target_info_changed_for_session_owner_background_event,
diff --git a/moli-protocol/src/domains/target/lifecycle.rs b/moli-protocol/src/domains/target/lifecycle.rs
index fdf2bf35d..775c78087 100644
--- a/moli-protocol/src/domains/target/lifecycle.rs
+++ b/moli-protocol/src/domains/target/lifecycle.rs
@@ -1,8 +1,9 @@
use serde::Deserialize;
use crate::conn::{
- BackgroundProtocolEvent, CdpTargetFilter, CdpTargetFilterEntry, PopupTargetNavigationKind,
- PopupTargetNavigationOwnerAction, PreparedTargetAttach, TargetAttachSessionCommit,
+ BackgroundProtocolEvent, CdpTargetFilter, CdpTargetFilterEntry, PopupTargetActivationAction,
+ PopupTargetNavigationKind, PopupTargetNavigationOwnerAction, PreparedTargetAttach,
+ TargetAttachSessionCommit,
};
use crate::devtools_runtime::{
DevToolsActivateTargetCommand, DevToolsBrowserContextId, DevToolsCloseTargetCommand,
@@ -488,6 +489,7 @@ pub(crate) struct PopupTargetCreation {
target_name: String,
opener: Option<PopupTargetOpenerIdentity>,
can_access_opener: bool,
+ disposition: moli_core::page::RendererPopupDisposition,
session_storage_store: Option<moli_core::network::SharedWebStorageStore>,
initial_empty_document_storage_key: Option<moli_storage_key::MoliStorageKey>,
}
@@ -500,6 +502,7 @@ impl PopupTargetCreation {
target_name: String,
opener: Option<PopupTargetOpenerIdentity>,
can_access_opener: bool,
+ disposition: moli_core::page::RendererPopupDisposition,
session_storage_store: Option<moli_core::network::SharedWebStorageStore>,
initial_empty_document_storage_key: Option<moli_storage_key::MoliStorageKey>,
) -> Self {
@@ -510,6 +513,7 @@ impl PopupTargetCreation {
target_name,
opener,
can_access_opener,
+ disposition,
session_storage_store,
initial_empty_document_storage_key,
}
@@ -528,6 +532,7 @@ pub(crate) async fn create_popup_target_from_renderer_output_background_events_a
target_name,
opener,
can_access_opener,
+ disposition,
session_storage_store,
initial_empty_document_storage_key,
} = creation;
@@ -557,6 +562,11 @@ pub(crate) async fn create_popup_target_from_renderer_output_background_events_a
)
})
.flatten();
+ let activation = (disposition == moli_core::page::RendererPopupDisposition::Foreground)
+ .then(|| {
+ PopupTargetActivationAction::capture(conn, &browser_context_id, &existing_target_id)
+ })
+ .flatten();
let target_url_updated = conn
.browser_context_by_id_mut(&browser_context_id)
@@ -573,6 +583,9 @@ pub(crate) async fn create_popup_target_from_renderer_output_background_events_a
if let Some(navigation) = navigation {
conn.publish_popup_target_navigation_owner_action(navigation);
}
+ if let Some(activation) = activation {
+ conn.publish_popup_target_activation_action(activation);
+ }
}
return (target_url_updated
&& remember_resolved_popup_target(
@@ -720,6 +733,12 @@ pub(crate) async fn create_popup_target_from_renderer_output_background_events_a
{
conn.publish_popup_target_navigation_owner_action(navigation);
}
+ if disposition == moli_core::page::RendererPopupDisposition::Foreground
+ && let Some(activation) =
+ PopupTargetActivationAction::capture(conn, &browser_context_id, &target_id)
+ {
+ conn.publish_popup_target_activation_action(activation);
+ }
Some(target_id)
}
@@ -960,6 +979,77 @@ pub(crate) async fn complete_popup_target_navigation_owner_action_async(
)
}
+pub(crate) async fn complete_popup_target_activation_action_async(
+ conn: &mut CdpConnection,
+ action: PopupTargetActivationAction,
+) -> crate::conn::CdpTurnOutcome {
+ let (owner_scope, browser_context_id, target_id) = action.into_parts();
+ let target_is_current = {
+ let mut route_scope = owner_scope.enter(conn);
+ let conn = route_scope.conn_mut();
+ conn.target_owner_identity_for_session(None).is_some_and(
+ |(current_browser_context_id, current_target_id)| {
+ current_browser_context_id == browser_context_id
+ && current_target_id.as_deref() == Some(target_id.as_str())
+ },
+ ) && popup_target_has_loaded_page(conn, &browser_context_id, &target_id)
+ };
+ if !target_is_current {
+ tracing::debug!(
+ browser_context_id,
+ target_id,
+ "dropping popup activation after its exact target owner retired"
+ );
+ return crate::conn::CdpTurnOutcome::new_with_protocol_events(
+ Vec::new(),
+ conn.take_scheduler_events(),
+ );
+ }
+ if let Err(error) = activate_popup_target_async(conn, &browser_context_id, &target_id).await {
+ tracing::debug!(
+ browser_context_id,
+ target_id,
+ %error,
+ "popup target could not be activated"
+ );
+ }
+ crate::conn::CdpTurnOutcome::new_with_protocol_events(Vec::new(), conn.take_scheduler_events())
+}
+
+async fn activate_popup_target_async(
+ conn: &mut CdpConnection,
+ browser_context_id: &str,
+ target_id: &str,
+) -> Result<(), String> {
+ let restore_browser_context_id = previously_active_browser_context_id(conn);
+ let result = if let Err(message) = select_browser_context_for_target(conn, target_id) {
+ Err(message.to_owned())
+ } else if conn
+ .browser_context
+ .as_ref()
+ .is_none_or(|browser_context| browser_context.id != browser_context_id)
+ {
+ Err("PopupTargetBrowserContextChanged".to_owned())
+ } else if conn
+ .browser_context
+ .as_ref()
+ .is_some_and(|browser_context| browser_context.is_active_target(target_id))
+ {
+ Ok(())
+ } else {
+ match conn
+ .promote_background_target_to_active_for_connection_async(target_id)
+ .await
+ {
+ Ok(true) => Ok(()),
+ Ok(false) => Err("PopupTargetUnavailable".to_owned()),
+ Err(message) => Err(message),
+ }
+ };
+ restore_previously_active_browser_context(conn, restore_browser_context_id.as_deref());
+ result
+}
+
pub(crate) fn emit_target_info_changed_for_session_owner_background_event(
conn: &mut CdpConnection,
out: &mut Vec<BackgroundProtocolEvent>,
diff --git a/moli-protocol/src/domains/target/tests/test_support.rs b/moli-protocol/src/domains/target/tests/test_support.rs
index 72522aa4f..bf2638027 100644
--- a/moli-protocol/src/domains/target/tests/test_support.rs
+++ b/moli-protocol/src/domains/target/tests/test_support.rs
@@ -38,6 +38,19 @@ pub(super) fn push_background_target(
));
}
+pub(super) fn loaded_page_for_target<'a>(
+ browser_context: &'a BrowserContext,
+ target_id: &str,
+) -> Option<&'a moli_core::page::Page> {
+ if browser_context.is_active_target(target_id) {
+ browser_context.loaded_page()
+ } else {
+ browser_context
+ .background_target(target_id)
+ .and_then(crate::conn::BackgroundTarget::loaded_page)
+ }
+}
+
pub(super) fn push_shared_worker_target(
ctx: &mut TestContext,
renderer_instance_id: SharedWorkerInstanceId,
diff --git a/moli-protocol/src/domains/target/tests/tests_background_staging.rs b/moli-protocol/src/domains/target/tests/tests_background_staging.rs
index 3acc82a9c..a0814f6e2 100644
--- a/moli-protocol/src/domains/target/tests/tests_background_staging.rs
+++ b/moli-protocol/src/domains/target/tests/tests_background_staging.rs
@@ -5058,7 +5058,7 @@ async fn same_context_loaded_background_window_open_self_navigates_owner_without
}
#[tokio::test(flavor = "multi_thread")]
-async fn same_context_named_popup_reuse_navigates_loaded_background_owner_without_promotion() {
+async fn same_context_named_popup_reuse_navigates_and_promotes_loaded_owner() {
let mut ctx = TestContext::new();
tokio::task::LocalSet::new()
.run_until(async {
@@ -5090,17 +5090,17 @@ async fn same_context_named_popup_reuse_navigates_loaded_background_owner_withou
assert_eq!(response["result"]["result"]["type"], json!("boolean"));
assert_eq!(response["result"]["result"]["value"], json!(true));
ctx.wait_until_scheduler_state(
- "named background popup navigation commit",
+ "named popup navigation commit and foreground activation",
|conn| {
conn.browser_context_by_id("BID-9-NAMED-POPUP")
- .and_then(|browser_context| browser_context.background_target(&owner.target_id))
- .is_some_and(|target| {
- target.target_url()
- == "data:text/html,<title>named</title><main>named target</main>"
- && target.loaded_page().is_some_and(|page| {
- page.final_url().as_str()
- == "data:text/html,<title>named</title><main>named target</main>"
- })
+ .is_some_and(|browser_context| {
+ browser_context.active_target_id() == Some(owner.target_id.as_str())
+ && loaded_page_for_target(browser_context, &owner.target_id).is_some_and(
+ |page| {
+ page.final_url().as_str()
+ == "data:text/html,<title>named</title><main>named target</main>"
+ },
+ )
})
},
)
@@ -5136,20 +5136,23 @@ async fn same_context_named_popup_reuse_navigates_loaded_background_owner_withou
let browser_context = ctx.conn.browser_context.as_ref().expect("browser context");
assert_eq!(
browser_context.active_target_id(),
- Some("TID-000000000NPA"),
- "named popup reuse must not promote the background target"
+ Some(owner.target_id.as_str()),
+ "ordinary window.open should promote its reused named target"
);
- let background_target = browser_context
- .background_target(&owner.target_id)
- .expect("background target should remain parked");
assert_eq!(
- background_target.target_url(),
+ browser_context.target_url(),
"data:text/html,<title>named</title><main>named target</main>"
);
assert!(
- background_target.has_loaded_page(),
+ browser_context.has_loaded_page(),
"named popup reuse should replace the existing owner loaded page"
);
+ assert!(
+ browser_context
+ .background_target("TID-000000000NPA")
+ .is_some(),
+ "foreground named-target reuse should demote the previous active target"
+ );
}
ctx.process_async(json!({
diff --git a/moli-protocol/src/domains/target/tests/tests_cdp_chromium_imports/p1_target_multipage.rs b/moli-protocol/src/domains/target/tests/tests_cdp_chromium_imports/p1_target_multipage.rs
index b58c6972d..7ca3030cb 100644
--- a/moli-protocol/src/domains/target/tests/tests_cdp_chromium_imports/p1_target_multipage.rs
+++ b/moli-protocol/src/domains/target/tests/tests_cdp_chromium_imports/p1_target_multipage.rs
@@ -668,8 +668,9 @@ async fn rust_cdp_chromium_target_window_open_auto_attached_popup_materializes_i
.expect("popup session id");
ctx.wait_until_scheduler_state("auto-attached popup navigation commit", |conn| {
conn.browser_context_by_id("BID-popup-auto-load")
- .and_then(|browser_context| browser_context.background_target(popup_target_id))
- .and_then(|target| target.loaded_page())
+ .and_then(|browser_context| {
+ loaded_page_for_target(browser_context, popup_target_id)
+ })
.is_some_and(|page| page.final_url().as_str() == popup_url)
})
.await;
@@ -677,8 +678,9 @@ async fn rust_cdp_chromium_target_window_open_auto_attached_popup_materializes_i
.conn
.browser_context
.as_ref()
- .and_then(|browser_context| browser_context.background_target(popup_target_id))
- .and_then(|target| target.loaded_page())
+ .and_then(|browser_context| {
+ loaded_page_for_target(browser_context, popup_target_id)
+ })
.expect("window.open lifecycle should have loaded the popup document");
assert_eq!(popup_page.final_url().as_str(), popup_url);
@@ -783,8 +785,9 @@ async fn rust_cdp_chromium_target_window_open_waiting_popup_routes_initial_docum
ctx.conn
.browser_context
.as_ref()
- .and_then(|browser_context| browser_context.background_target(popup_target_id))
- .and_then(|target| target.loaded_page())
+ .and_then(|browser_context| {
+ loaded_page_for_target(browser_context, popup_target_id)
+ })
.is_some_and(|page| page.final_url().as_str() == "about:blank"),
"popup target lifecycle should already expose the initial about:blank document"
);
diff --git a/moli-protocol/src/domains/target/tests/tests_target_creation.rs b/moli-protocol/src/domains/target/tests/tests_target_creation.rs
index feed99e91..a5ebda810 100644
--- a/moli-protocol/src/domains/target/tests/tests_target_creation.rs
+++ b/moli-protocol/src/domains/target/tests/tests_target_creation.rs
@@ -1051,6 +1051,18 @@ async fn window_open_hands_off_session_storage_snapshot_and_initial_storage_key(
ctx.enable_background_navigation_scheduler_for_test();
tokio::task::LocalSet::new().run_until(async {
+ ctx.process_async(json!({
+ "id": 1200,
+ "method": "Target.attachToTarget",
+ "params": { "targetId": "TID-popup-storage-opener" }
+ }))
+ .await;
+ let opener_session_id = take_response_by_id(&mut ctx, 1200)["result"]["sessionId"]
+ .as_str()
+ .expect("opener session id")
+ .to_owned();
+ ctx.sent.clear();
+
ctx.process_async(json!({
"id": 1201,
"method": "Runtime.evaluate",
@@ -1133,8 +1145,9 @@ async fn window_open_hands_off_session_storage_snapshot_and_initial_storage_key(
"attached popup cross-origin navigation commit",
|conn| {
conn.browser_context_by_id("BID-popup-storage")
- .and_then(|browser_context| browser_context.background_target(&popup_target_id))
- .and_then(|target| target.loaded_page())
+ .and_then(|browser_context| {
+ loaded_page_for_target(browser_context, &popup_target_id)
+ })
.is_some_and(|page| page.final_url().as_str() == first_cross_origin_url)
},
)
@@ -1166,6 +1179,7 @@ async fn window_open_hands_off_session_storage_snapshot_and_initial_storage_key(
ctx.process_async(json!({
"id": 1204,
"method": "Runtime.evaluate",
+ "sessionId": opener_session_id,
"params": {
"expression": format!(
"(() => {{ sessionStorage.setItem('cross-origin-secret', 'opener-only'); return window.open({cross_origin_url:?}, '_blank') !== null; }})()"
@@ -1182,7 +1196,7 @@ async fn window_open_hands_off_session_storage_snapshot_and_initial_storage_key(
"value": true
}
}),
- None,
+ Some(&opener_session_id),
);
let cross_origin_created = ctx
.sent
@@ -1252,9 +1266,8 @@ async fn window_open_hands_off_session_storage_snapshot_and_initial_storage_key(
|conn| {
conn.browser_context_by_id("BID-popup-storage")
.and_then(|browser_context| {
- browser_context.background_target(&cross_origin_target_id)
+ loaded_page_for_target(browser_context, &cross_origin_target_id)
})
- .and_then(|target| target.loaded_page())
.is_some_and(|page| page.final_url().as_str() == cross_origin_url)
},
)
@@ -1679,17 +1692,30 @@ async fn window_open_named_target_reuses_existing_popup_target() {
"<main>popup opener</main>",
)
.await;
+ ctx.process_async(json!({
+ "id": 12,
+ "method": "Target.attachToTarget",
+ "params": { "targetId": "TID-opener-name" }
+ }))
+ .await;
+ let opener_session_id = take_response_by_id(&mut ctx, 12)["result"]["sessionId"]
+ .as_str()
+ .expect("opener session id")
+ .to_owned();
+ ctx.sent.clear();
ctx.process_async(json!({
"id": 13,
- "method": "Page.enable"
+ "method": "Page.enable",
+ "sessionId": opener_session_id
}))
.await;
- ctx.expect_result(13, json!({}), None);
+ ctx.expect_result(13, json!({}), Some(&opener_session_id));
ctx.sent.clear();
ctx.process_async(json!({
"id": 14,
"method": "Runtime.evaluate",
+ "sessionId": opener_session_id,
"params": {
"expression": "window.open('data:text/html,first-popup', 'reportWindow') !== null"
}
@@ -1719,6 +1745,7 @@ async fn window_open_named_target_reuses_existing_popup_target() {
ctx.process_async(json!({
"id": 15,
"method": "Runtime.evaluate",
+ "sessionId": opener_session_id,
"params": {
"expression": "window.open('data:text/html,second-popup', 'reportWindow') !== null"
}
@@ -1761,11 +1788,22 @@ async fn window_open_named_target_reuses_existing_popup_target() {
changed["params"]["targetInfo"]["url"],
json!("data:text/html,second-popup")
);
+ ctx.wait_until_scheduler_state("reused named popup remains selected", |conn| {
+ conn.browser_context_by_id("BID-popup-name")
+ .is_some_and(|browser_context| {
+ browser_context.active_target_id() == Some(target_id.as_str())
+ && loaded_page_for_target(browser_context, &target_id).is_some_and(
+ |page| {
+ page.final_url().as_str() == "data:text/html,second-popup"
+ },
+ )
+ })
+ })
+ .await;
let browser_context = ctx.conn.browser_context.as_ref().unwrap();
- assert_eq!(browser_context.background_targets.len(), 1);
- assert_eq!(browser_context.background_targets[0].target_id(), target_id);
+ assert_eq!(browser_context.active_target_id(), Some(target_id.as_str()));
assert_eq!(
- browser_context.background_targets[0].target_url(),
+ browser_context.target_url(),
"data:text/html,second-popup"
);
})
@@ -1960,6 +1998,215 @@ async fn anchor_blank_target_uses_implicit_noopener() {
);
}
+async fn dispatch_anchor_left_click(ctx: &mut TestContext, command_id: u64, modifiers: u8) {
+ for (offset, event_type, buttons) in [(0, "mousePressed", 1), (1, "mouseReleased", 0)] {
+ ctx.process_async(json!({
+ "id": command_id + offset,
+ "method": "Input.dispatchMouseEvent",
+ "params": {
+ "type": event_type,
+ "x": 20,
+ "y": 20,
+ "button": "left",
+ "buttons": buttons,
+ "clickCount": 1,
+ "modifiers": modifiers
+ }
+ }))
+ .await;
+ ctx.expect_result(command_id + offset, json!({}), None);
+ }
+}
+
+fn popup_target_id_for_url(messages: &[serde_json::Value], url: &str) -> String {
+ messages
+ .iter()
+ .find(|message| {
+ message["method"] == json!("Target.targetCreated")
+ && message["params"]["targetInfo"]["type"] == json!("page")
+ && message["params"]["targetInfo"]["url"] == json!(url)
+ })
+ .and_then(|message| message["params"]["targetInfo"]["targetId"].as_str())
+ .unwrap_or_else(|| panic!("anchor click should create an exact page target: {messages:#?}"))
+ .to_owned()
+}
+
+#[tokio::test(flavor = "multi_thread")]
+async fn anchor_left_click_promotes_blank_target_to_foreground() {
+ const POPUP_HREF: &str = "data:text/html,%3Cmain%3Eforeground-popup%3C/main%3E";
+ const POPUP_URL: &str = "data:text/html,<main>foreground-popup</main>";
+ let mut ctx = TestContext::new();
+ ctx.enable_background_navigation_scheduler_for_test();
+ tokio::task::LocalSet::new()
+ .run_until(async {
+ load_bc_with_titled_page_async(
+ &mut ctx,
+ "BID-anchor-foreground",
+ "TID-anchor-foreground-opener",
+ &format!(
+ "<a href='{POPUP_HREF}' target='_blank' style='position:absolute;left:0;top:0;width:100px;height:100px;display:block'>popup</a>"
+ ),
+ )
+ .await;
+ let _ = ctx.take_all();
+
+ dispatch_anchor_left_click(&mut ctx, 16_100, 0).await;
+
+ let sent = ctx.take_all();
+ let popup_target_id = popup_target_id_for_url(&sent, POPUP_URL);
+ let browser_context = ctx
+ .conn
+ .browser_context_by_id("BID-anchor-foreground")
+ .expect("anchor browser context should remain available");
+ assert_eq!(
+ browser_context.active_target_id(),
+ Some(popup_target_id.as_str())
+ );
+ assert!(
+ browser_context
+ .background_target("TID-anchor-foreground-opener")
+ .is_some(),
+ "foreground popup should demote its opener"
+ );
+ })
+ .await;
+}
+
+#[tokio::test(flavor = "multi_thread")]
+async fn anchor_left_click_activates_popup_while_initial_navigation_waits_for_debugger() {
+ const POPUP_HREF: &str =
+ "data:text/html,%3Cmain%3Edebugger-waiting-foreground-popup%3C/main%3E";
+ const POPUP_URL: &str = "data:text/html,<main>debugger-waiting-foreground-popup</main>";
+ let mut ctx = TestContext::new();
+ ctx.enable_background_navigation_scheduler_for_test();
+ tokio::task::LocalSet::new()
+ .run_until(async {
+ load_bc_with_titled_page_async(
+ &mut ctx,
+ "BID-anchor-debugger-wait",
+ "TID-anchor-debugger-wait-opener",
+ &format!(
+ "<a href='{POPUP_HREF}' target='_blank' style='position:absolute;left:0;top:0;width:100px;height:100px;display:block'>popup</a>"
+ ),
+ )
+ .await;
+ let _ = ctx.take_all();
+ ctx.process_async(json!({
+ "id": 16_150,
+ "method": "Target.setAutoAttach",
+ "params": {
+ "autoAttach": true,
+ "waitForDebuggerOnStart": true,
+ "flatten": true
+ }
+ }))
+ .await;
+ ctx.expect_result(16_150, json!({}), None);
+ let _ = ctx.take_all();
+
+ dispatch_anchor_left_click(&mut ctx, 16_151, 0).await;
+
+ let sent = ctx.take_all();
+ let popup_target_id = popup_target_id_for_url(&sent, POPUP_URL);
+ let popup_session_id = sent
+ .iter()
+ .find(|message| {
+ message["method"] == json!("Target.attachedToTarget")
+ && message["params"]["targetInfo"]["type"] == json!("page")
+ && message["params"]["targetInfo"]["targetId"]
+ == json!(popup_target_id)
+ })
+ .and_then(|message| message["params"]["sessionId"].as_str())
+ .unwrap_or_else(|| {
+ panic!("foreground popup should be auto-attached: {sent:#?}")
+ })
+ .to_owned();
+ let browser_context = ctx
+ .conn
+ .browser_context_by_id("BID-anchor-debugger-wait")
+ .expect("anchor browser context should remain available");
+ assert_eq!(
+ browser_context.active_target_id(),
+ Some(popup_target_id.as_str()),
+ "foreground selection must not wait for initial navigation"
+ );
+ assert!(
+ browser_context
+ .active_target
+ .runtime_slot
+ .loaded_page()
+ .is_some_and(|page| moli_url::is_about_blank(page.final_url())),
+ "waitForDebuggerOnStart should retain the active popup's initial about:blank document"
+ );
+
+ ctx.process_async(json!({
+ "id": 16_153,
+ "method": "Runtime.runIfWaitingForDebugger",
+ "sessionId": popup_session_id
+ }))
+ .await;
+ ctx.expect_result(16_153, json!({}), Some(&popup_session_id));
+ ctx.wait_until_scheduler_state("resumed foreground popup navigation", |conn| {
+ conn.browser_context_by_id("BID-anchor-debugger-wait")
+ .is_some_and(|browser_context| {
+ browser_context.active_target_id() == Some(popup_target_id.as_str())
+ && browser_context
+ .active_target
+ .runtime_slot
+ .loaded_page()
+ .is_some_and(|page| page.final_url().as_str() == POPUP_URL)
+ })
+ })
+ .await;
+ })
+ .await;
+}
+
+#[tokio::test(flavor = "multi_thread")]
+async fn anchor_platform_new_tab_click_keeps_blank_target_in_background() {
+ const POPUP_HREF: &str = "data:text/html,%3Cmain%3Ebackground-popup%3C/main%3E";
+ const POPUP_URL: &str = "data:text/html,<main>background-popup</main>";
+ let mut ctx = TestContext::new();
+ ctx.enable_background_navigation_scheduler_for_test();
+ tokio::task::LocalSet::new()
+ .run_until(async {
+ load_bc_with_titled_page_async(
+ &mut ctx,
+ "BID-anchor-background",
+ "TID-anchor-background-opener",
+ &format!(
+ "<a href='{POPUP_HREF}' target='_blank' style='position:absolute;left:0;top:0;width:100px;height:100px;display:block'>popup</a>"
+ ),
+ )
+ .await;
+ let _ = ctx.take_all();
+
+ #[cfg(target_os = "macos")]
+ let platform_new_tab_modifier = 4;
+ #[cfg(not(target_os = "macos"))]
+ let platform_new_tab_modifier = 2;
+ dispatch_anchor_left_click(&mut ctx, 16_200, platform_new_tab_modifier).await;
+
+ let sent = ctx.take_all();
+ let popup_target_id = popup_target_id_for_url(&sent, POPUP_URL);
+ let browser_context = ctx
+ .conn
+ .browser_context_by_id("BID-anchor-background")
+ .expect("anchor browser context should remain available");
+ assert_eq!(
+ browser_context.active_target_id(),
+ Some("TID-anchor-background-opener")
+ );
+ assert!(
+ browser_context
+ .background_target(&popup_target_id)
+ .is_some(),
+ "platform-new-tab-clicked popup should remain in the background"
+ );
+ })
+ .await;
+}
+
#[tokio::test(flavor = "multi_thread")]
async fn anchor_blank_target_with_rel_opener_preserves_exact_opener() {
let mut ctx = TestContext::new();
diff --git a/moli-renderer-v8/src/context_bootstrap/window_runtime/dialogs.rs b/moli-renderer-v8/src/context_bootstrap/window_runtime/dialogs.rs
index 925c8f615..95054a8f4 100644
--- a/moli-renderer-v8/src/context_bootstrap/window_runtime/dialogs.rs
+++ b/moli-renderer-v8/src/context_bootstrap/window_runtime/dialogs.rs
@@ -240,6 +240,9 @@ pub(crate) fn window_open_callback<'s>(
let window_open_event = opened_popup
.created_new_browsing_context
.then_some(window_open_event);
+ let popup_disposition = host
+ .current_input_popup_disposition()
+ .unwrap_or(crate::RendererPopupDisposition::Foreground);
host.record_pending_popup_activation(
RendererPendingPopupActivation::window(
root_document,
@@ -248,6 +251,7 @@ pub(crate) fn window_open_callback<'s>(
Some(popup_id),
url,
parsed.target_name,
+ popup_disposition,
)
.with_initial_auxiliary_state(
session_storage_store,
@@ -262,6 +266,9 @@ pub(crate) fn window_open_callback<'s>(
}
return;
}
+ let popup_disposition = host
+ .current_input_popup_disposition()
+ .unwrap_or(crate::RendererPopupDisposition::Foreground);
host.record_pending_popup_activation(
RendererPendingPopupActivation::window(
root_document,
@@ -270,6 +277,7 @@ pub(crate) fn window_open_callback<'s>(
None,
url,
parsed.target_name,
+ popup_disposition,
)
.with_initial_auxiliary_state(None, None),
Some(window_open_event),
diff --git a/moli-renderer-v8/src/lib.rs b/moli-renderer-v8/src/lib.rs
index c163ac0e5..0dfb5841e 100644
--- a/moli-renderer-v8/src/lib.rs
+++ b/moli-renderer-v8/src/lib.rs
@@ -281,20 +281,20 @@ pub use runtime::{
RendererPendingPopupActivation, RendererPendingSameDocumentNavigation,
RendererPendingTopLevelHistoryTraversal, RendererPendingWindowOpenEvent,
RendererPerformanceMetricSnapshot, RendererPointerEventProperties,
- RendererPopupActivationSource, RendererPreparedDocumentCommitConfiguration,
- RendererProtocolObservation, RendererReservedServiceWorkerClient,
- RendererResourceTextSearchOutcome, RendererRuntimeCommandCausalIdentity,
- RendererRuntimeCommandOutput, RendererRuntimeEvaluationResult, RendererRuntimeHeapSpaceUsage,
- RendererRuntimeHeapUsage, RendererRuntimeInspectorAsyncCompletion,
- RendererRuntimeInspectorIoCommandClaim, RendererRuntimeInspectorIoCommandRoute,
- RendererRuntimeInspectorMainCommandCompletion, RendererRuntimeInspectorMainCommandRoute,
- RendererRuntimeInspectorMessage, RendererRuntimeInspectorMessageBatch,
- RendererRuntimeInspectorProtocolMessage, RendererRuntimeInspectorProtocolMessageValueMut,
- RendererRuntimeInspectorResponseChannel, RendererRuntimeInspectorResponseSender,
- RendererRuntimeObservableSourceItem, RendererRuntimeObservableSourceSummary,
- RendererRuntimeRealmInfo, RendererRuntimeRemoteObject, RendererRuntimeRemoteObjectResolution,
- RendererScreenshotClip, RendererScreenshotFormat, RendererScreenshotPurpose,
- RendererScreenshotRegion, RendererScriptExecutionMemoryDiagnostics,
+ RendererPopupActivationSource, RendererPopupDisposition,
+ RendererPreparedDocumentCommitConfiguration, RendererProtocolObservation,
+ RendererReservedServiceWorkerClient, RendererResourceTextSearchOutcome,
+ RendererRuntimeCommandCausalIdentity, RendererRuntimeCommandOutput,
+ RendererRuntimeEvaluationResult, RendererRuntimeHeapSpaceUsage, RendererRuntimeHeapUsage,
+ RendererRuntimeInspectorAsyncCompletion, RendererRuntimeInspectorIoCommandClaim,
+ RendererRuntimeInspectorIoCommandRoute, RendererRuntimeInspectorMainCommandCompletion,
+ RendererRuntimeInspectorMainCommandRoute, RendererRuntimeInspectorMessage,
+ RendererRuntimeInspectorMessageBatch, RendererRuntimeInspectorProtocolMessage,
+ RendererRuntimeInspectorProtocolMessageValueMut, RendererRuntimeInspectorResponseChannel,
+ RendererRuntimeInspectorResponseSender, RendererRuntimeObservableSourceItem,
+ RendererRuntimeObservableSourceSummary, RendererRuntimeRealmInfo, RendererRuntimeRemoteObject,
+ RendererRuntimeRemoteObjectResolution, RendererScreenshotClip, RendererScreenshotFormat,
+ RendererScreenshotPurpose, RendererScreenshotRegion, RendererScriptExecutionMemoryDiagnostics,
RendererScriptSourceMemoryDiagnostics, RendererScrollIntoViewResult,
RendererServiceWorkerConsoleMessage, RendererServiceWorkerExceptionMessage,
RendererServiceWorkerFetchDiagnostic, RendererServiceWorkerFetchDiagnosticResult,
diff --git a/moli-renderer-v8/src/native_bridge/context_host/core.rs b/moli-renderer-v8/src/native_bridge/context_host/core.rs
index 8a0d14b5c..9e0cdaa69 100644
--- a/moli-renderer-v8/src/native_bridge/context_host/core.rs
+++ b/moli-renderer-v8/src/native_bridge/context_host/core.rs
@@ -267,6 +267,7 @@ impl JsContextHost {
timezone_override: None,
idle_override: None,
protocol_user_gesture_activation_depth: 0,
+ current_input_popup_disposition: None,
webdriver_bidi_file_prompt_handler_stack: Vec::new(),
emulated_media: crate::protocol_types::EmulatedMediaOverrides::default(),
viewport_surface: None,
diff --git a/moli-renderer-v8/src/native_bridge/context_host/host_environment.rs b/moli-renderer-v8/src/native_bridge/context_host/host_environment.rs
index fae3223fb..7b4de935c 100644
--- a/moli-renderer-v8/src/native_bridge/context_host/host_environment.rs
+++ b/moli-renderer-v8/src/native_bridge/context_host/host_environment.rs
@@ -747,6 +747,19 @@ impl JsContextHost {
self.protocol_user_gesture_activation_depth > 0
}
+ pub(crate) fn replace_current_input_popup_disposition(
+ &mut self,
+ disposition: Option<crate::RendererPopupDisposition>,
+ ) -> Option<crate::RendererPopupDisposition> {
+ std::mem::replace(&mut self.current_input_popup_disposition, disposition)
+ }
+
+ pub(crate) fn current_input_popup_disposition(
+ &self,
+ ) -> Option<crate::RendererPopupDisposition> {
+ self.current_input_popup_disposition
+ }
+
pub(crate) fn begin_webdriver_bidi_file_prompt_handler(&mut self, handler: &str) {
self.webdriver_bidi_file_prompt_handler_stack
.push(handler.to_owned());
diff --git a/moli-renderer-v8/src/native_bridge/context_host/mod.rs b/moli-renderer-v8/src/native_bridge/context_host/mod.rs
index 86db14fb9..6072434dc 100644
--- a/moli-renderer-v8/src/native_bridge/context_host/mod.rs
+++ b/moli-renderer-v8/src/native_bridge/context_host/mod.rs
@@ -869,6 +869,7 @@ pub(crate) struct JsContextHost {
timezone_override: Option<String>,
idle_override: Option<crate::protocol_types::EmulatedIdleOverride>,
protocol_user_gesture_activation_depth: usize,
+ current_input_popup_disposition: Option<crate::RendererPopupDisposition>,
webdriver_bidi_file_prompt_handler_stack: Vec<String>,
emulated_media: crate::protocol_types::EmulatedMediaOverrides,
viewport_surface: Option<crate::protocol_types::ViewportSurface>,
diff --git a/moli-renderer-v8/src/native_bridge/element/activation/default_action.rs b/moli-renderer-v8/src/native_bridge/element/activation/default_action.rs
index d2322ac61..5e9b845b6 100644
--- a/moli-renderer-v8/src/native_bridge/element/activation/default_action.rs
+++ b/moli-renderer-v8/src/native_bridge/element/activation/default_action.rs
@@ -9,7 +9,7 @@ use crate::util::{
};
use crate::{
RendererInputDispatchOutcome, RendererPendingDownloadActivation,
- RendererPendingFileChooserActivation,
+ RendererPendingFileChooserActivation, RendererPopupDisposition,
document_runtime::{DomHandle, EventTargetHandle},
frame_owner_model::DocumentId,
native_bridge::context_host::ChildBrowsingContextBootstrap,
@@ -741,6 +741,44 @@ fn click_handle_internal(
click_detail: i32,
modifiers: u8,
user_initiated: bool,
+) -> RendererInputDispatchOutcome {
+ let popup_disposition = current_click_popup_disposition(button, modifiers, user_initiated);
+ let previous_popup_disposition = unsafe { &mut *runtime_ptr }
+ .replace_current_input_popup_disposition(Some(popup_disposition));
+ let outcome = click_handle_internal_with_current_input(
+ scope,
+ runtime_ptr,
+ handle,
+ x,
+ y,
+ button,
+ buttons,
+ click_detail,
+ modifiers,
+ user_initiated,
+ );
+ let replaced_popup_disposition = unsafe { &mut *runtime_ptr }
+ .replace_current_input_popup_disposition(previous_popup_disposition);
+ assert_eq!(
+ replaced_popup_disposition,
+ Some(popup_disposition),
+ "the current click popup disposition must remain scoped to its activation"
+ );
+ outcome
+}
+
+#[allow(clippy::too_many_arguments)]
+fn click_handle_internal_with_current_input(
+ scope: &mut v8::PinScope<'_, '_>,
+ runtime_ptr: *mut JsContextHost,
+ handle: DomHandle,
+ x: f64,
+ y: f64,
+ button: i32,
+ buttons: i32,
+ click_detail: i32,
+ modifiers: u8,
+ user_initiated: bool,
) -> RendererInputDispatchOutcome {
let runtime = unsafe { &*runtime_ptr };
if is_disabled_form_control(runtime, handle) {
@@ -815,6 +853,7 @@ fn click_handle_internal(
handle,
x,
y,
+ button,
modifiers,
user_initiated,
&pending_child_navigations_before_default,
@@ -875,6 +914,7 @@ fn click_handle_internal(
handle,
x,
y,
+ button,
modifiers,
user_initiated,
&pending_child_navigations_before_default,
@@ -922,6 +962,7 @@ fn click_handle_internal(
handle,
x,
y,
+ button,
modifiers,
user_initiated,
&pending_child_navigations_before_click,
@@ -1147,8 +1188,19 @@ pub(crate) fn perform_click_default_action_for_dispatched_event(
}
let x = object_number_property(scope, event, "clientX").unwrap_or(0.0);
let y = object_number_property(scope, event, "clientY").unwrap_or(0.0);
+ let button = object_number_property(scope, event, "button").unwrap_or(0.0) as i32;
let modifiers = mouse_event_modifier_bits(scope, event);
- let _ = perform_click_default_action(scope, runtime_ptr, handle, x, y, modifiers, false, &[]);
+ let _ = perform_click_default_action(
+ scope,
+ runtime_ptr,
+ handle,
+ x,
+ y,
+ button,
+ modifiers,
+ false,
+ &[],
+ );
}
pub(crate) enum DispatchedClickLegacyActivation {
@@ -1292,6 +1344,7 @@ fn perform_click_default_action(
handle: DomHandle,
x: f64,
y: f64,
+ button: i32,
modifiers: u8,
user_initiated: bool,
pending_child_navigations_before_default: &[(DomHandle, ChildBrowsingContextBootstrap)],
@@ -1302,6 +1355,8 @@ fn perform_click_default_action(
scope,
runtime_ptr,
handle,
+ button,
+ modifiers,
user_initiated,
pending_child_navigations_before_default,
);
@@ -1777,6 +1832,8 @@ fn anchor_click_default_action(
scope: &mut v8::PinScope<'_, '_>,
runtime_ptr: *mut JsContextHost,
handle: DomHandle,
+ button: i32,
+ modifiers: u8,
user_initiated: bool,
pending_child_navigations_before_default: &[(DomHandle, ChildBrowsingContextBootstrap)],
) -> Option<RendererPendingDownloadActivation> {
@@ -1787,31 +1844,41 @@ fn anchor_click_default_action(
send_anchor_ping_requests(scope, runtime_ptr, handle, &resolved);
let runtime = unsafe { &*runtime_ptr };
if element_has_attribute(runtime, handle, "download") {
- let download_request = element_attribute(runtime, handle, "download").unwrap_or_default();
- let source_element = node_wrapper_from_handle(scope, handle);
- let proceed = navigation_owner_window_for_handle(scope, runtime_ptr, handle).is_none_or(
- |owner| {
- crate::context_bootstrap::dispatch_cross_document_navigation_navigate_event_for_window(
- scope,
- owner,
- &resolved,
- source_element,
- user_initiated,
- Some(&download_request),
- )
- },
+ let suggested_filename =
+ element_attribute(runtime, handle, "download").filter(|value| !value.is_empty());
+ return anchor_download_activation(
+ scope,
+ runtime_ptr,
+ handle,
+ resolved,
+ user_initiated,
+ suggested_filename,
+ );
+ }
+ let navigation_policy = hyperlink_navigation_policy(button, modifiers, user_initiated);
+ if navigation_policy == HyperlinkNavigationPolicy::Download {
+ return anchor_download_activation(
+ scope,
+ runtime_ptr,
+ handle,
+ resolved,
+ user_initiated,
+ None,
);
- if !proceed {
- return None;
- }
- return Some(RendererPendingDownloadActivation {
- url: resolved,
- suggested_filename: (!download_request.is_empty()).then_some(download_request),
- response: None,
- });
}
- let target_name =
+ let declared_target_name =
element_attribute(runtime, handle, "target").filter(|value| !value.is_empty());
+ let (target_name, popup_disposition) = match navigation_policy {
+ HyperlinkNavigationPolicy::Auxiliary(disposition) => {
+ (Some("_blank".to_owned()), disposition)
+ }
+ HyperlinkNavigationPolicy::Current => {
+ (declared_target_name, RendererPopupDisposition::Foreground)
+ }
+ HyperlinkNavigationPolicy::Download => {
+ unreachable!("download hyperlink policy returned before target selection")
+ }
+ };
let special_target = target_name
.as_deref()
.and_then(SpecialBrowsingContextTarget::parse);
@@ -1905,10 +1972,94 @@ fn anchor_click_default_action(
target_name.as_deref(),
&resolved,
source_element,
+ popup_disposition,
);
None
}
+fn anchor_download_activation(
+ scope: &mut v8::PinScope<'_, '_>,
+ runtime_ptr: *mut JsContextHost,
+ handle: DomHandle,
+ resolved: String,
+ user_initiated: bool,
+ suggested_filename: Option<String>,
+) -> Option<RendererPendingDownloadActivation> {
+ let source_element = node_wrapper_from_handle(scope, handle);
+ let download_request = suggested_filename.as_deref().unwrap_or("");
+ let proceed =
+ navigation_owner_window_for_handle(scope, runtime_ptr, handle).is_none_or(|owner| {
+ crate::context_bootstrap::dispatch_cross_document_navigation_navigate_event_for_window(
+ scope,
+ owner,
+ &resolved,
+ source_element,
+ user_initiated,
+ Some(download_request),
+ )
+ });
+ proceed.then_some(RendererPendingDownloadActivation {
+ url: resolved,
+ suggested_filename,
+ response: None,
+ })
+}
+
+#[derive(Clone, Copy, Debug, Eq, PartialEq)]
+enum HyperlinkNavigationPolicy {
+ Current,
+ Download,
+ Auxiliary(RendererPopupDisposition),
+}
+
+fn hyperlink_navigation_policy(
+ button: i32,
+ modifiers: u8,
+ user_initiated: bool,
+) -> HyperlinkNavigationPolicy {
+ const ALT: u8 = 1;
+ const SHIFT: u8 = 8;
+
+ #[cfg(target_os = "macos")]
+ let platform_new_tab_modifier = 4;
+ #[cfg(not(target_os = "macos"))]
+ let platform_new_tab_modifier = 2;
+
+ let requests_new_tab = button == 1 || modifiers & platform_new_tab_modifier != 0;
+ let shift = modifiers & SHIFT != 0;
+ let alt = modifiers & ALT != 0;
+ if requests_new_tab {
+ let disposition = if shift || !user_initiated {
+ RendererPopupDisposition::Foreground
+ } else {
+ RendererPopupDisposition::Background
+ };
+ HyperlinkNavigationPolicy::Auxiliary(disposition)
+ } else if shift {
+ // The renderer target model has no separate window chrome. Preserve
+ // Chromium's selected-surface behavior by folding a new window into a
+ // foreground auxiliary target.
+ HyperlinkNavigationPolicy::Auxiliary(RendererPopupDisposition::Foreground)
+ } else if alt && user_initiated {
+ HyperlinkNavigationPolicy::Download
+ } else {
+ HyperlinkNavigationPolicy::Current
+ }
+}
+
+fn current_click_popup_disposition(
+ button: i32,
+ modifiers: u8,
+ user_initiated: bool,
+) -> RendererPopupDisposition {
+ match hyperlink_navigation_policy(button, modifiers, user_initiated) {
+ HyperlinkNavigationPolicy::Auxiliary(disposition) => disposition,
+ HyperlinkNavigationPolicy::Current | HyperlinkNavigationPolicy::Download => {
+ RendererPopupDisposition::Foreground
+ }
+ }
+}
+
fn click_listener_changed_named_child_navigation(
scope: &mut v8::PinScope<'_, '_>,
runtime_ptr: *mut JsContextHost,
@@ -2220,3 +2371,79 @@ pub(in crate::native_bridge) fn navigate_form_target_browsing_context(
exposes_opener,
)
}
+
+#[cfg(test)]
+mod hyperlink_popup_disposition_tests {
+ use super::*;
+
+ const CTRL: u8 = 2;
+ const META: u8 = 4;
+ const SHIFT: u8 = 8;
+ const ALT: u8 = 1;
+
+ #[cfg(target_os = "macos")]
+ const PLATFORM_NEW_TAB_MODIFIER: u8 = META;
+ #[cfg(not(target_os = "macos"))]
+ const PLATFORM_NEW_TAB_MODIFIER: u8 = CTRL;
+
+ #[cfg(target_os = "macos")]
+ const NON_PLATFORM_NEW_TAB_MODIFIER: u8 = CTRL;
+ #[cfg(not(target_os = "macos"))]
+ const NON_PLATFORM_NEW_TAB_MODIFIER: u8 = META;
+
+ #[test]
+ fn ordinary_click_uses_the_declared_target() {
+ assert_eq!(
+ hyperlink_navigation_policy(0, 0, true),
+ HyperlinkNavigationPolicy::Current
+ );
+ assert_eq!(
+ hyperlink_navigation_policy(0, NON_PLATFORM_NEW_TAB_MODIFIER, true),
+ HyperlinkNavigationPolicy::Current
+ );
+ }
+
+ #[test]
+ fn trusted_new_context_input_matches_chromium_surface_selection() {
+ assert_eq!(
+ hyperlink_navigation_policy(1, 0, true),
+ HyperlinkNavigationPolicy::Auxiliary(RendererPopupDisposition::Background)
+ );
+ assert_eq!(
+ hyperlink_navigation_policy(0, PLATFORM_NEW_TAB_MODIFIER, true),
+ HyperlinkNavigationPolicy::Auxiliary(RendererPopupDisposition::Background)
+ );
+ assert_eq!(
+ hyperlink_navigation_policy(0, SHIFT, true),
+ HyperlinkNavigationPolicy::Auxiliary(RendererPopupDisposition::Foreground)
+ );
+ assert_eq!(
+ hyperlink_navigation_policy(1, SHIFT, true),
+ HyperlinkNavigationPolicy::Auxiliary(RendererPopupDisposition::Foreground)
+ );
+ }
+
+ #[test]
+ fn synthetic_new_tab_input_cannot_create_a_background_tab_under() {
+ assert_eq!(
+ hyperlink_navigation_policy(1, 0, false),
+ HyperlinkNavigationPolicy::Auxiliary(RendererPopupDisposition::Foreground)
+ );
+ assert_eq!(
+ hyperlink_navigation_policy(0, PLATFORM_NEW_TAB_MODIFIER, false),
+ HyperlinkNavigationPolicy::Auxiliary(RendererPopupDisposition::Foreground)
+ );
+ }
+
+ #[test]
+ fn only_trusted_alt_click_requests_a_download() {
+ assert_eq!(
+ hyperlink_navigation_policy(0, ALT, true),
+ HyperlinkNavigationPolicy::Download
+ );
+ assert_eq!(
+ hyperlink_navigation_policy(0, ALT, false),
+ HyperlinkNavigationPolicy::Current
+ );
+ }
+}
diff --git a/moli-renderer-v8/src/native_bridge/element/activation/targets.rs b/moli-renderer-v8/src/native_bridge/element/activation/targets.rs
index af15f1438..eb5c34c7a 100644
--- a/moli-renderer-v8/src/native_bridge/element/activation/targets.rs
+++ b/moli-renderer-v8/src/native_bridge/element/activation/targets.rs
@@ -1,5 +1,5 @@
use crate::{
- RendererPendingPopupActivation, RendererPendingWindowOpenEvent,
+ RendererPendingPopupActivation, RendererPendingWindowOpenEvent, RendererPopupDisposition,
context_bootstrap::dispatch_cross_document_navigation_navigate_event_for_window,
document_runtime::{DocumentPolicyContainer, DomHandle},
native_bridge::context_host::ChildBrowsingContextNavigationRequest,
@@ -89,6 +89,7 @@ fn queue_popup_target_navigation(
None,
resolved_url.to_owned(),
target_name.to_owned(),
+ RendererPopupDisposition::Foreground,
)
.with_initial_auxiliary_state(None, None),
Some(window_open_event),
@@ -176,6 +177,7 @@ fn navigate_hyperlink_popup_target(
source_handle: DomHandle,
target_name: &str,
resolved_url: &str,
+ disposition: RendererPopupDisposition,
) -> bool {
let relations = hyperlink_popup_relations(unsafe { &*runtime_ptr }, source_handle, target_name);
let Some(dispatch_scope) =
@@ -203,6 +205,7 @@ fn navigate_hyperlink_popup_target(
None,
resolved_url.to_owned(),
target_name.to_owned(),
+ disposition,
)
.with_initial_auxiliary_state(None, None),
Some(window_open_event),
@@ -239,6 +242,7 @@ fn navigate_hyperlink_popup_target(
None,
resolved_url.to_owned(),
target_name.to_owned(),
+ disposition,
)
.with_initial_auxiliary_state(None, None),
Some(window_open_event),
@@ -261,6 +265,7 @@ fn navigate_hyperlink_popup_target(
Some(popup_id),
resolved_url.to_owned(),
target_name.to_owned(),
+ disposition,
)
.with_initial_auxiliary_state(session_storage_store, initial_empty_document_storage_key),
window_open_event,
@@ -485,6 +490,7 @@ pub(in crate::native_bridge) fn navigate_hyperlink_target_browsing_context<'s>(
target_name: Option<&str>,
resolved_url: &str,
source_element: Option<v8::Local<'s, v8::Object>>,
+ popup_disposition: RendererPopupDisposition,
) -> bool {
if !hyperlink_javascript_url_allowed_by_csp(scope, runtime_ptr, source_handle, resolved_url) {
return true;
@@ -497,6 +503,7 @@ pub(in crate::native_bridge) fn navigate_hyperlink_target_browsing_context<'s>(
source_handle,
"_blank",
resolved_url,
+ popup_disposition,
);
}
if let Some(target_name) = target_name
@@ -514,6 +521,7 @@ pub(in crate::native_bridge) fn navigate_hyperlink_target_browsing_context<'s>(
source_handle,
target_name,
resolved_url,
+ popup_disposition,
);
}
let Some(dispatch_scope) =
diff --git a/moli-renderer-v8/src/runtime/mod.rs b/moli-renderer-v8/src/runtime/mod.rs
index 5fdd81210..8972bd1fc 100644
--- a/moli-renderer-v8/src/runtime/mod.rs
+++ b/moli-renderer-v8/src/runtime/mod.rs
@@ -347,23 +347,24 @@ pub use self::page_surface::{
RendererPendingPopupActivation, RendererPendingSameDocumentNavigation,
RendererPendingTopLevelHistoryTraversal, RendererPendingWindowOpenEvent,
RendererPerformanceMetricSnapshot, RendererPointerEventProperties,
- RendererPopupActivationSource, RendererResourceTextSearchOutcome, RendererRuntimeCommandOutput,
- RendererRuntimeEvaluationResult, RendererRuntimeHeapSpaceUsage, RendererRuntimeHeapUsage,
- RendererRuntimeInspectorAsyncCompletion, RendererRuntimeInspectorMessage,
- RendererRuntimeInspectorMessageBatch, RendererRuntimeInspectorProtocolMessage,
- RendererRuntimeInspectorProtocolMessageValueMut, RendererRuntimeInspectorResponseChannel,
- RendererRuntimeInspectorResponseSender, RendererRuntimeObservableSourceItem,
- RendererRuntimeObservableSourceSummary, RendererRuntimeRealmInfo, RendererRuntimeRemoteObject,
- RendererRuntimeRemoteObjectResolution, RendererScriptExecutionMemoryDiagnostics,
- RendererScriptSourceMemoryDiagnostics, RendererScrollIntoViewResult,
- RendererServiceWorkerConsoleMessage, RendererServiceWorkerExceptionMessage,
- RendererServiceWorkerFetchDiagnostic, RendererServiceWorkerFetchDiagnosticResult,
- RendererServiceWorkerTargetEvent, RendererServiceWorkerTargetInfo,
- RendererServiceWorkerVersionStatus, RendererSetDocumentContentResult,
- RendererSharedWorkerConsoleMessage, RendererSharedWorkerTargetEvent,
- RendererSharedWorkerTargetInfo, RendererStyleSheetHeader, RendererStyleSheetInventoryUpdate,
- RendererStyleSheetPayload, RendererSyntheticResponseBody, RendererTextSearchMatch,
- RendererTouchPoint, RendererWindowDocumentSource, RuntimeConsoleMessageSnapshot,
+ RendererPopupActivationSource, RendererPopupDisposition, RendererResourceTextSearchOutcome,
+ RendererRuntimeCommandOutput, RendererRuntimeEvaluationResult, RendererRuntimeHeapSpaceUsage,
+ RendererRuntimeHeapUsage, RendererRuntimeInspectorAsyncCompletion,
+ RendererRuntimeInspectorMessage, RendererRuntimeInspectorMessageBatch,
+ RendererRuntimeInspectorProtocolMessage, RendererRuntimeInspectorProtocolMessageValueMut,
+ RendererRuntimeInspectorResponseChannel, RendererRuntimeInspectorResponseSender,
+ RendererRuntimeObservableSourceItem, RendererRuntimeObservableSourceSummary,
+ RendererRuntimeRealmInfo, RendererRuntimeRemoteObject, RendererRuntimeRemoteObjectResolution,
+ RendererScriptExecutionMemoryDiagnostics, RendererScriptSourceMemoryDiagnostics,
+ RendererScrollIntoViewResult, RendererServiceWorkerConsoleMessage,
+ RendererServiceWorkerExceptionMessage, RendererServiceWorkerFetchDiagnostic,
+ RendererServiceWorkerFetchDiagnosticResult, RendererServiceWorkerTargetEvent,
+ RendererServiceWorkerTargetInfo, RendererServiceWorkerVersionStatus,
+ RendererSetDocumentContentResult, RendererSharedWorkerConsoleMessage,
+ RendererSharedWorkerTargetEvent, RendererSharedWorkerTargetInfo, RendererStyleSheetHeader,
+ RendererStyleSheetInventoryUpdate, RendererStyleSheetPayload, RendererSyntheticResponseBody,
+ RendererTextSearchMatch, RendererTouchPoint, RendererWindowDocumentSource,
+ RuntimeConsoleMessageSnapshot,
};
pub(crate) use self::page_surface::{
RendererCommandTurnOutputRecorder, RendererDevToolsSessionOutputHost,
diff --git a/moli-renderer-v8/src/runtime/page_surface.rs b/moli-renderer-v8/src/runtime/page_surface.rs
index 8f8009087..ff1470777 100644
--- a/moli-renderer-v8/src/runtime/page_surface.rs
+++ b/moli-renderer-v8/src/runtime/page_surface.rs
@@ -32,7 +32,9 @@ mod window_document_source;
pub use javascript_dialog::{
RendererJavaScriptDialogId, RendererJavaScriptDialogSource, RendererPendingJavaScriptDialog,
};
-pub use popup_activation::{RendererPendingPopupActivation, RendererPopupActivationSource};
+pub use popup_activation::{
+ RendererPendingPopupActivation, RendererPopupActivationSource, RendererPopupDisposition,
+};
pub use window_document_source::RendererWindowDocumentSource;
#[derive(Debug, Clone)]
diff --git a/moli-renderer-v8/src/runtime/page_surface/popup_activation.rs b/moli-renderer-v8/src/runtime/page_surface/popup_activation.rs
index 9f661f834..c0babd6c6 100644
--- a/moli-renderer-v8/src/runtime/page_surface/popup_activation.rs
+++ b/moli-renderer-v8/src/runtime/page_surface/popup_activation.rs
@@ -24,6 +24,17 @@ pub enum RendererPopupActivationSource {
BrowserContext,
}
+/// Browser-owner selection policy for an accepted auxiliary browsing context.
+///
+/// This records only whether the target should become the active target. It
+/// deliberately does not distinguish tab and window chrome, which the
+/// renderer target model does not expose.
+#[derive(Clone, Copy, Debug, Eq, PartialEq)]
+pub enum RendererPopupDisposition {
+ Foreground,
+ Background,
+}
+
/// A renderer-accepted request to create or reuse an auxiliary browsing
/// context.
///
@@ -34,6 +45,7 @@ pub enum RendererPopupActivationSource {
#[derive(Debug, Clone)]
pub struct RendererPendingPopupActivation {
source: RendererPopupActivationSource,
+ disposition: RendererPopupDisposition,
popup_id: Option<u64>,
url: String,
target_name: String,
@@ -49,6 +61,7 @@ impl RendererPendingPopupActivation {
popup_id: Option<u64>,
url: String,
target_name: String,
+ disposition: RendererPopupDisposition,
) -> Self {
assert!(
!is_special_browsing_context_target(&target_name),
@@ -60,6 +73,7 @@ impl RendererPendingPopupActivation {
window,
exposes_opener,
},
+ disposition,
popup_id,
url,
target_name,
@@ -68,13 +82,19 @@ impl RendererPendingPopupActivation {
}
}
- pub fn browser_context(popup_id: Option<u64>, url: String, target_name: String) -> Self {
+ pub fn browser_context(
+ popup_id: Option<u64>,
+ url: String,
+ target_name: String,
+ disposition: RendererPopupDisposition,
+ ) -> Self {
assert!(
!is_special_browsing_context_target(&target_name),
"browser-context popup activation must not carry a special target"
);
Self {
source: RendererPopupActivationSource::BrowserContext,
+ disposition,
popup_id,
url,
target_name,
@@ -106,6 +126,10 @@ impl RendererPendingPopupActivation {
&self.source
}
+ pub fn disposition(&self) -> RendererPopupDisposition {
+ self.disposition
+ }
+
pub fn popup_id(&self) -> Option<u64> {
self.popup_id
}
@@ -123,6 +147,7 @@ impl RendererPendingPopupActivation {
self,
) -> (
RendererPopupActivationSource,
+ RendererPopupDisposition,
Option<u64>,
String,
String,
@@ -131,6 +156,7 @@ impl RendererPendingPopupActivation {
) {
(
self.source,
+ self.disposition,
self.popup_id,
self.url,
self.target_name,
@@ -143,6 +169,7 @@ impl RendererPendingPopupActivation {
impl PartialEq for RendererPendingPopupActivation {
fn eq(&self, other: &Self) -> bool {
self.source == other.source
+ && self.disposition == other.disposition
&& self.popup_id == other.popup_id
&& self.url == other.url
&& self.target_name == other.target_name
diff --git a/moli-renderer-v8/src/script_vm/service_worker_internal_client_request_body.rs b/moli-renderer-v8/src/script_vm/service_worker_internal_client_request_body.rs
index a7e5921db..d261a40dd 100644
--- a/moli-renderer-v8/src/script_vm/service_worker_internal_client_request_body.rs
+++ b/moli-renderer-v8/src/script_vm/service_worker_internal_client_request_body.rs
@@ -267,6 +267,7 @@ impl ScriptVm {
popup_id,
url.clone(),
"_blank".to_owned(),
+ crate::RendererPopupDisposition::Foreground,
)
.with_initial_auxiliary_state(
session_storage_store,
@@ -348,6 +349,7 @@ impl ScriptVm {
popup_id,
url.clone(),
"_blank".to_owned(),
+ crate::RendererPopupDisposition::Foreground,
)
.with_initial_auxiliary_state(
session_storage_store,
diff --git a/moli-renderer-v8/src/script_vm/tests/browser_api/misc.rs b/moli-renderer-v8/src/script_vm/tests/browser_api/misc.rs
index 1e6131fc1..2377edfcf 100644
--- a/moli-renderer-v8/src/script_vm/tests/browser_api/misc.rs
+++ b/moli-renderer-v8/src/script_vm/tests/browser_api/misc.rs
@@ -20464,6 +20464,10 @@ async fn service_worker_clients_open_window_request_records_popup_activation() {
popups[0].source(),
crate::RendererPopupActivationSource::BrowserContext
));
+ assert_eq!(
+ popups[0].disposition(),
+ crate::RendererPopupDisposition::Foreground
+ );
assert!(vm.has_pending_lightweight_popup_document_loads());
drain_service_worker_test_until_popup_loads_settle(
diff --git a/moli-renderer-v8/src/script_vm/tests/browser_api/navigation.rs b/moli-renderer-v8/src/script_vm/tests/browser_api/navigation.rs
index 147719119..279eccaec 100644
--- a/moli-renderer-v8/src/script_vm/tests/browser_api/navigation.rs
+++ b/moli-renderer-v8/src/script_vm/tests/browser_api/navigation.rs
@@ -43,6 +43,11 @@ fn form_target_blank_reloads_rel_opener_policy_for_each_submission() {
exposes_opener, &expected_exposes_opener,
"rel={rel:?} opener policy"
);
+ assert_eq!(
+ activations[0].disposition(),
+ crate::RendererPopupDisposition::Foreground,
+ "target=_blank form submission should select its new surface"
+ );
}
}
diff --git a/moli-renderer-v8/src/script_vm/tests/dom_xhr/forms.rs b/moli-renderer-v8/src/script_vm/tests/dom_xhr/forms.rs
index c7137c93d..d30f8ce96 100644
--- a/moli-renderer-v8/src/script_vm/tests/dom_xhr/forms.rs
+++ b/moli-renderer-v8/src/script_vm/tests/dom_xhr/forms.rs
@@ -3674,6 +3674,153 @@ fn anchor_download_synthetic_click_records_pending_download_without_navigation()
);
}
+#[test]
+fn trusted_alt_click_downloads_an_anchor_without_a_download_attribute() {
+ let mut vm = new_parsed_test_vm(
+ "https://anchor-alt-download.test/path/index.html",
+ r#"<!doctype html><html><head><style>
+ body { margin: 0; }
+ #download_link { display: block; width: 100px; height: 100px; }
+ </style></head><body>
+ <a id="download_link" href="/download.txt">download</a>
+ </body></html>"#,
+ );
+
+ vm.dispatch_mouse_event_at_point_with_pointer_and_modifiers(
+ 20.0,
+ 20.0,
+ "mousedown",
+ 0,
+ None,
+ 1,
+ 0.0,
+ 0.0,
+ crate::runtime::RendererPointerEventProperties::default(),
+ 1,
+ )
+ .expect("alt mousedown should dispatch");
+ let outcome = vm
+ .dispatch_mouse_event_at_point_with_pointer_and_modifiers(
+ 20.0,
+ 20.0,
+ "mouseup",
+ 0,
+ None,
+ 1,
+ 0.0,
+ 0.0,
+ crate::runtime::RendererPointerEventProperties::default(),
+ 1,
+ )
+ .expect("alt mouseup should dispatch");
+
+ let pending_download = outcome
+ .pending_download
+ .expect("trusted alt click should request a download");
+ assert_eq!(
+ pending_download.url,
+ "https://anchor-alt-download.test/download.txt"
+ );
+ assert!(pending_download.suggested_filename.is_none());
+ assert!(vm.take_pending_location_navigation_with_seed().is_none());
+ assert!(vm.take_pending_popup_activations().is_empty());
+}
+
+#[test]
+fn window_open_in_click_listener_uses_current_input_popup_disposition() {
+ #[cfg(target_os = "macos")]
+ let (platform_modifier, synthetic_modifier) = (4, "metaKey: true");
+ #[cfg(not(target_os = "macos"))]
+ let (platform_modifier, synthetic_modifier) = (2, "ctrlKey: true");
+
+ let mut trusted = new_storage_test_vm("https://window-open-input-policy.test/path/index.html");
+ trusted
+ .eval(
+ r#"
+(() => {
+ const html = document.createElement('html');
+ const body = document.createElement('body');
+ body.style.margin = '0';
+ const button = document.createElement('button');
+ button.id = 'go';
+ button.type = 'button';
+ button.style.cssText = 'display:block;width:100px;height:100px';
+ button.onclick = () => window.open('/trusted', '_blank');
+ body.appendChild(button);
+ html.appendChild(body);
+ document.appendChild(html);
+})()
+"#,
+ )
+ .expect("trusted window.open fixture should initialize");
+ trusted
+ .dispatch_mouse_event_at_point_with_pointer_and_modifiers(
+ 20.0,
+ 20.0,
+ "mousedown",
+ 0,
+ None,
+ 1,
+ 0.0,
+ 0.0,
+ crate::runtime::RendererPointerEventProperties::default(),
+ platform_modifier,
+ )
+ .expect("new-tab-modified mousedown should dispatch");
+ trusted
+ .dispatch_mouse_event_at_point_with_pointer_and_modifiers(
+ 20.0,
+ 20.0,
+ "mouseup",
+ 0,
+ None,
+ 1,
+ 0.0,
+ 0.0,
+ crate::runtime::RendererPointerEventProperties::default(),
+ platform_modifier,
+ )
+ .expect("new-tab-modified mouseup should dispatch");
+ let trusted_popups = trusted.take_pending_popup_activations();
+ assert_eq!(trusted_popups.len(), 1);
+ assert_eq!(
+ trusted_popups[0].disposition(),
+ crate::RendererPopupDisposition::Background
+ );
+
+ let mut synthetic =
+ new_storage_test_vm("https://window-open-synthetic-policy.test/path/index.html");
+ synthetic
+ .eval(
+ r#"
+(() => {
+ const html = document.createElement('html');
+ const body = document.createElement('body');
+ const button = document.createElement('button');
+ button.id = 'go';
+ button.type = 'button';
+ button.onclick = () => window.open('/synthetic', '_blank');
+ body.appendChild(button);
+ html.appendChild(body);
+ document.appendChild(html);
+})()
+"#,
+ )
+ .expect("synthetic window.open fixture should initialize");
+ synthetic
+ .eval(&format!(
+ "go.dispatchEvent(new MouseEvent('click', {{ button: 0, {synthetic_modifier} }})); 'done'"
+ ))
+ .expect("synthetic modified click should dispatch");
+ let synthetic_popups = synthetic.take_pending_popup_activations();
+ assert_eq!(synthetic_popups.len(), 1);
+ assert_eq!(
+ synthetic_popups[0].disposition(),
+ crate::RendererPopupDisposition::Foreground,
+ "a synthesized modifier cannot create a tab-under"
+ );
+}
+
#[test]
fn keyboard_activation_click_preserves_modifiers() {
let mut vm = new_parsed_test_vm(