diff --git a/moli-renderer-v8/src/native_bridge/context_host/popups.rs b/moli-renderer-v8/src/native_bridge/context_host/popups.rs index 2710117d796..90d8f9c82dc 100644 --- a/moli-renderer-v8/src/native_bridge/context_host/popups.rs +++ b/moli-renderer-v8/src/native_bridge/context_host/popups.rs @@ -752,9 +752,20 @@ impl PageScriptHost { if let Some(document_handle) = document_handle { let _ = self.set_dom_document_url_for_handle(document_handle, url.clone()); } - let base_url = self - .lightweight_popup_base_url(scope, popup_id) + let base_url = document_handle + .map(|document| self.document_base_url_for_handle(document)) + .or_else(|| self.lightweight_popup_base_url(scope, popup_id)) .unwrap_or_else(|| url.clone()); + if let Some(record) = self.lightweight_popup_document_record_mut(popup_id) { + record.state.base_url = base_url.clone(); + } + if let Some(owner) = self.current_lightweight_popup_document_owner(popup_id) + && let Some(loader) = self.document_resource_loader_for_window_owner( + super::WindowDocumentOwner::LightweightPopup(owner), + ) + { + loader.update_document_urls(url.clone(), base_url.clone()); + } if let Some(document) = self.lightweight_popup_document_wrapper(scope, popup_id) { // Keep the Document's exposed URL slots in sync before history // events run, without reinstalling its author-visible methods. @@ -5710,6 +5721,10 @@ impl PageScriptHost { document: v8::Local<'s, v8::Object>, ) { debug_assert!(std::ptr::eq(host_ptr, self)); + let owner = self + .lightweight_popup_id_for_document_handle(document_handle) + .and_then(|popup_id| self.current_lightweight_popup_document_owner(popup_id)); + let entry_document = self.document_open_entry_document(scope); crate::native_bridge::document::set_detached_html_document_body_html( scope, host_ptr, @@ -5719,21 +5734,38 @@ impl PageScriptHost { unsafe { &*host_ptr } .reset_meta_content_security_policy_processing_for_document(document_handle); set_lightweight_popup_document_write_session(scope, document, true); + if let Some(owner) = owner + && self.lightweight_popup_document_owner_is_current(owner) + && let Some(entry_document) = entry_document + { + let popup_id = owner.popup_id(); + let url = self.document_open_replacement_url(document_handle, entry_document); + self.set_lightweight_popup_same_document_url(scope, popup_id, url.clone()); + if let Some(window) = self.lightweight_popup_window(scope, popup_id) { + // Publish native state before the history update can dispatch + // author callbacks that perform another URL change. + crate::context_bootstrap::update_history_for_document_open(scope, window, &url); + } + // Initial about:blank suppresses Navigation API events during + // the URL/history update. Clear it only after that update. + if let Some(record) = self.lightweight_popup_document_record_mut(popup_id) + && record.owner == owner + { + record.is_initial_empty_document = false; + } + } } pub(in crate::native_bridge) fn write_lightweight_popup_document_stream<'s>( &mut self, scope: &mut v8::PinScope<'s, '_>, host_ptr: *mut PageScriptHost, - popup_id: u64, document_handle: DomHandle, document: v8::Local<'s, v8::Object>, html: &str, ) { debug_assert!(std::ptr::eq(host_ptr, self)); - let writing_during_load = active_lightweight_popup_id(scope) == Some(popup_id) - && !lightweight_popup_document_write_session_active(scope, document); - if writing_during_load { + if !lightweight_popup_document_write_session_active(scope, document) { self.open_lightweight_popup_document_stream(scope, host_ptr, document_handle, document); } crate::native_bridge::document::append_detached_html_document_body_html( diff --git a/moli-renderer-v8/src/native_bridge/document/lifecycle.rs b/moli-renderer-v8/src/native_bridge/document/lifecycle.rs index 247dcbc817b..feed9f16b9e 100644 --- a/moli-renderer-v8/src/native_bridge/document/lifecycle.rs +++ b/moli-renderer-v8/src/native_bridge/document/lifecycle.rs @@ -128,13 +128,13 @@ fn node_document_write_or_writeln_callback<'s>( ); return; } - if let Some(popup_id) = - unsafe { &*runtime_ptr }.lightweight_popup_id_for_document_handle(handle) + if unsafe { &*runtime_ptr } + .lightweight_popup_id_for_document_handle(handle) + .is_some() { unsafe { &mut *runtime_ptr }.write_lightweight_popup_document_stream( scope, runtime_ptr, - popup_id, handle, args.this(), &html, diff --git a/moli-renderer-v8/src/network/context/document.rs b/moli-renderer-v8/src/network/context/document.rs index 0d098a0db16..b1437b975b9 100644 --- a/moli-renderer-v8/src/network/context/document.rs +++ b/moli-renderer-v8/src/network/context/document.rs @@ -295,6 +295,21 @@ impl DocumentResourceLoader { self.authority.lifecycle.lock().context.clone() } + /// Updates the URL inputs for later loads without changing this Document's + /// origin, authority, or requests that already captured their settings. + pub(crate) fn update_document_urls(&self, document_url: url::Url, base_url: url::Url) { + let mut lifecycle = self.authority.lifecycle.lock(); + if lifecycle.state != DocumentResourceLoaderState::Active { + return; + } + lifecycle.context = DocumentFetchContext::new( + lifecycle.context.owner(), + document_url, + base_url, + lifecycle.context.origin().to_owned(), + ); + } + #[cfg(test)] pub(crate) fn owner(&self) -> crate::native_bridge::WindowDocumentOwner { self.authority.lifecycle.lock().context.owner() diff --git a/moli-renderer-v8/src/script_vm/tests/browser_api/mod.rs b/moli-renderer-v8/src/script_vm/tests/browser_api/mod.rs index ed99f457d84..6a52d4465bf 100644 --- a/moli-renderer-v8/src/script_vm/tests/browser_api/mod.rs +++ b/moli-renderer-v8/src/script_vm/tests/browser_api/mod.rs @@ -71,6 +71,7 @@ mod platform_identity; mod pointer_capture; mod pointer_lock; mod pointing_event_init; +mod popup_document_open_url; mod popup_document_stream; mod popup_hyperlinks; mod promise_rejection; diff --git a/moli-renderer-v8/src/script_vm/tests/browser_api/popup_document_open_url.rs b/moli-renderer-v8/src/script_vm/tests/browser_api/popup_document_open_url.rs new file mode 100644 index 00000000000..d8ef69ebbfc --- /dev/null +++ b/moli-renderer-v8/src/script_vm/tests/browser_api/popup_document_open_url.rs @@ -0,0 +1,246 @@ +use super::*; + +#[test] +fn popup_document_open_updates_url_history_and_resource_context_from_entry() { + let mut vm = new_storage_test_vm("https://popup-open-url.test/entry/page?query#fragment"); + let main_owner = vm.current_main_document_task_owner(); + vm.eval( + r#" +const root = document.appendChild(document.createElement('html')); +const head = root.appendChild(document.createElement('head')); +root.appendChild(document.createElement('body')); +const base = head.appendChild(document.createElement('base')); +base.href = '/different-base/'; +globalThis.__urlPopup = open(); +"#, + ) + .unwrap(); + let popup_id = vm.take_pending_popup_activations()[0].popup_id().unwrap(); + let loader = vm + .with_default_context_scope(|_, host_ptr| { + let host = unsafe { &*host_ptr }; + let owner = host + .current_lightweight_popup_document_owner(popup_id) + .unwrap(); + Ok(host + .document_resource_loader_for_window_owner( + crate::native_bridge::WindowDocumentOwner::LightweightPopup(owner), + ) + .unwrap() + .clone()) + }) + .unwrap(); + let captured = loader.fetch_context(); + let result = vm + .eval( + r#" +(() => { + const w = __urlPopup, d = w.document; + w.history.replaceState({map:new Map([['kept',42]])}, ''); + const state = w.history.state, length = w.history.length; + const same = d.open() === d; + const a = d.createElement('a'); a.href = 'relative'; + const after = [same,w.document === d,d.URL,d.documentURI,d.baseURI,w.location.href, + w.history.length === length,w.history.state === state,state.map.get('kept'),a.href]; + w.history.pushState(null, '', '?next'); + after.push(w.history.length === length + 1); + d.close(); + return JSON.stringify(after); +})() +"#, + ) + .unwrap(); + assert_eq!( + result, + r#"[true,true,"https://popup-open-url.test/entry/page?query","https://popup-open-url.test/entry/page?query","https://popup-open-url.test/entry/page?query","https://popup-open-url.test/entry/page?query",true,true,42,"https://popup-open-url.test/entry/relative",true]"# + ); + let current = loader.fetch_context(); + assert_eq!(captured.document_url().as_str(), "about:blank"); + assert_eq!( + captured.base_url().as_str(), + "https://popup-open-url.test/different-base/" + ); + assert_eq!( + current.document_url().as_str(), + "https://popup-open-url.test/entry/page?next" + ); + assert_eq!(current.base_url(), current.document_url()); + assert_eq!(current.owner(), captured.owner()); + assert_eq!(current.origin(), captured.origin()); + assert_eq!(current.origin(), "https://popup-open-url.test"); + assert_eq!(vm.current_main_document_task_owner(), main_owner); + vm.eval("__urlPopup.close()").unwrap(); +} + +#[tokio::test] +async fn popup_document_open_and_implicit_write_update_loaded_popup_urls() { + let loader = ResourceRequestClient::new(&moli_fetch::FetchConfig::default()).unwrap(); + let mut vm = new_parsed_page_task_executor_test_vm( + "https://popup-open-loaded.test/entry?query#fragment", + "opener", + &loader, + ); + vm.eval( + r#" +window.__loadedUrlPopups = []; +window.__loadedUrlResults = []; +window.__loadedUrlReady = () => { + for (const [mode,w] of __loadedUrlPopups) { + const d = w.document, expected = document.URL.split('#')[0]; + w.history.replaceState({kept:42}, ''); + const state = w.history.state, length = w.history.length; + let same = true; + if (mode === 'borrowed') same = Document.prototype.open.call(d) === d; + else if (mode === 'write' || mode === 'writeln') d[mode]('replacement'); + else same = d.open() === d; + __loadedUrlResults.push([mode,same,d === w.document,d.URL === expected, + d.documentURI === expected,d.baseURI === expected,w.location.href === expected, + w.history.state === state,w.history.length === length, + d.body.textContent]); + d.close(); + } +}; +window.__loadedUrlCount = 0; +const source = URL.createObjectURL(new Blob(['original'], {type:'text/html'})); +for (const mode of ['open','borrowed','write','writeln']) { + const w = open(source); + __loadedUrlPopups.push([mode,w]); + w.addEventListener('load', () => { + ++__loadedUrlCount; + }, {once:true}); +} +"#, + ) + .unwrap(); + advance_page_task_executor_until_eval_equals( + &mut vm, + &loader, + "String(__loadedUrlCount)", + "4", + "loaded popup document.open URLs", + ) + .await; + vm.eval("__loadedUrlReady()").unwrap(); + assert_eq!( + vm.eval("JSON.stringify(__loadedUrlResults)").unwrap(), + r#"[["open",true,true,true,true,true,true,true,true,""],["borrowed",true,true,true,true,true,true,true,true,""],["write",true,true,true,true,true,true,true,true,"replacement"],["writeln",true,true,true,true,true,true,true,true,"replacement\n"]]"# + ); + vm.eval("__loadedUrlPopups.forEach(([,w]) => w.close())") + .unwrap(); +} + +#[tokio::test] +async fn popup_document_open_uses_popup_entry_and_preserves_self_fragment() { + let loader = ResourceRequestClient::new(&moli_fetch::FetchConfig::default()).unwrap(); + let mut vm = new_parsed_page_task_executor_test_vm( + "https://popup-open-entry.test/root#root-fragment", + "opener", + &loader, + ); + vm.eval( + r#" +window.__entryTarget = open(); +window.__entryUrlResults = []; +window.__entryUrlPopups = ['self','other'].map(mode => { + const html = `original`; + return open(URL.createObjectURL(new Blob([html],{type:'text/html'})) + '#popup-fragment'); +}); +"#, + ) + .unwrap(); + advance_page_task_executor_until_eval_equals( + &mut vm, + &loader, + "String(__entryUrlResults.length)", + "2", + "popup entry document URL", + ) + .await; + assert_eq!( + vm.eval("JSON.stringify(__entryUrlResults.sort())").unwrap(), + r#"[["other",true,true,true,true,true],["self",true,true,true,true,true]]"# + ); + vm.eval("__entryUrlPopups.forEach(w=>w.close()); __entryTarget.close();") + .unwrap(); +} + +#[tokio::test] +async fn popup_document_open_keeps_reentrant_history_update_last() { + let loader = ResourceRequestClient::new(&moli_fetch::FetchConfig::default()).unwrap(); + let mut vm = new_parsed_page_task_executor_test_vm( + "https://popup-open-reentrant.test/entry#fragment", + "opener", + &loader, + ); + vm.eval(r#" +window.__reentrantLoaded = false; +window.__reentrantPopup = open(URL.createObjectURL(new Blob([''],{type:'text/html'}))); +__reentrantPopup.addEventListener('load',()=>{__reentrantLoaded=true},{once:true}); +"#).unwrap(); + advance_page_task_executor_until_eval_equals( + &mut vm, + &loader, + "String(__reentrantLoaded)", + "true", + "loaded popup history callback", + ) + .await; + let result = vm + .eval( + r#" +(() => { + const w = __reentrantPopup, d = w.document; + let count = 0; + try { + w.navigation.addEventListener('currententrychange', () => { + ++count; + w.history.replaceState({nested:true}, '', '/nested#final'); + }, {once:true}); + d.open(); + d.close(); + return JSON.stringify([count,d.URL,d.documentURI,d.baseURI,w.location.href,w.history.state]); + } finally { w.close(); } +})() +"#, + ) + .unwrap(); + assert_eq!( + result, + r#"[1,"https://popup-open-reentrant.test/nested#final","https://popup-open-reentrant.test/nested#final","https://popup-open-reentrant.test/nested#final","https://popup-open-reentrant.test/nested#final",{"nested":true}]"# + ); +} + +#[test] +fn popup_document_open_updates_initial_document_before_queued_close() { + let mut vm = new_storage_test_vm("https://popup-open-closing.test/entry#fragment"); + let result = vm + .eval( + r#" +(() => { + const w = open(), d = w.document; + let changes = 0; + w.navigation.addEventListener('currententrychange',()=>++changes); + w.close(); + const same = d.open() === d; + d.close(); + return JSON.stringify([same,d.URL,d.documentURI,d.baseURI,changes]); +})() +"#, + ) + .unwrap(); + assert_eq!( + result, + r#"[true,"https://popup-open-closing.test/entry","https://popup-open-closing.test/entry","https://popup-open-closing.test/entry",0]"# + ); +}