Skip to main content

script/dom/window/
windowproxy.rs

1/* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at https://mozilla.org/MPL/2.0/. */
4
5use std::cell::Cell;
6use std::collections::HashSet;
7use std::ptr::{self, NonNull};
8use std::rc::Rc;
9
10use content_security_policy::sandboxing_directive::SandboxingFlagSet;
11use dom_struct::dom_struct;
12use html5ever::local_name;
13use indexmap::map::IndexMap;
14use itertools::Either;
15use js::JSCLASS_IS_GLOBAL;
16use js::context::JSContext;
17use js::gc::{HandleId, HandleObject, HandleValue, MutableHandleObject};
18use js::glue::{
19    CreateWrapperProxyHandler, DeleteWrapperProxyHandler, GetProxyPrivate, GetProxyReservedSlot,
20    ProxyTraps, SetProxyReservedSlot,
21};
22use js::jsapi::{
23    GCContext, Handle as RawHandle, HandleId as RawHandleId, HandleObject as RawHandleObject,
24    HandleValue as RawHandleValue, JS_DefinePropertyById, JS_DeletePropertyById,
25    JS_ForwardSetPropertyTo, JSContext as RawJSContext, JSErrNum, JSITER_HIDDEN, JSITER_OWNONLY,
26    JSITER_SYMBOLS, JSObject, JSPROP_ENUMERATE, JSPROP_READONLY, JSTracer,
27    MutableHandle as RawMutableHandle, MutableHandleIdVector as RawMutableHandleIdVector,
28    MutableHandleObject as RawMutableHandleObject, MutableHandleValue as RawMutableHandleValue,
29    ObjectOpResult, PropertyDescriptor, jsid,
30};
31use js::jsval::{NullValue, PrivateValue, UndefinedValue};
32use js::realm::{AutoRealm, CurrentRealm};
33use js::rust::wrappers2::{
34    AppendToIdVector, JS_ForwardGetPropertyTo, JS_HasOwnPropertyById, JS_HasPropertyById,
35    JS_TransplantObject, NewWindowProxy, SetWindowProxy, int_to_jsid,
36};
37use js::rust::{Handle, MutableHandle, MutableHandleValue, get_object_class};
38use js::typedarray::JSObjectStorage;
39use malloc_size_of::{MallocSizeOf, MallocSizeOfOps};
40use net_traits::ReferrerPolicy;
41use net_traits::request::Referrer;
42use script_bindings::cell::DomRefCell;
43use script_bindings::codegen::GenericBindings::DissimilarOriginWindowBinding::{
44    self, DissimilarOriginWindowMethods,
45};
46use script_bindings::codegen::GenericBindings::HTMLIFrameElementBinding::HTMLIFrameElementMethods;
47use script_bindings::codegen::GenericBindings::WindowBinding::{
48    self, GetProtoObject, WindowMethods,
49};
50use script_bindings::conversions::jsid_to_string;
51use script_bindings::domstring::TracedDOMString;
52use script_bindings::js::{GetPropertyKeys, JS_GetOwnPropertyDescriptorById};
53use script_bindings::proxyhandler::{
54    self, CROSS_ORIGIN_PROPERTY_HOLDER_WEAK_MAP_SLOT, CrossOriginProperties,
55    cross_origin_get_own_property_helper, cross_origin_own_property_keys,
56    cross_origin_property_fallback, cross_origin_set, is_extensible,
57    is_platform_object_same_origin, maybe_cross_origin_get_prototype,
58    maybe_cross_origin_set_prototype_rawcx, prevent_extensions, report_cross_origin_denial,
59    set_property_descriptor,
60};
61use script_bindings::reflector::{DomObject, MutDomObject, Reflector};
62use script_traits::{NewPipelineInfo, WebViewState};
63use serde::{Deserialize, Serialize};
64use servo_base::generic_channel;
65use servo_base::generic_channel::GenericSend;
66use servo_base::id::{BrowsingContextId, PipelineId, WebViewId};
67use servo_constellation_traits::{
68    AuxiliaryWebViewCreationRequest, LoadData, LoadOrigin, NavigationHistoryBehavior,
69    ScriptToConstellationMessage, TargetSnapshotParams,
70};
71use servo_url::{ImmutableOrigin, OriginSnapshot, ServoUrl};
72use storage_traits::webstorage_thread::WebStorageThreadMsg;
73use style::attr::parse_integer;
74
75use crate::DomTypeHolder;
76use crate::dom::bindings::conversions::{ToJSValConvertible, root_from_handleobject};
77use crate::dom::bindings::error::{Error, Fallible};
78use crate::dom::bindings::inheritance::Castable;
79use crate::dom::bindings::reflector::DomGlobal;
80use crate::dom::bindings::root::{Dom, DomRoot};
81use crate::dom::bindings::settings_stack::maybe_entry_global;
82use crate::dom::bindings::str::{DOMString, USVString};
83use crate::dom::bindings::trace::JSTraceable;
84use crate::dom::bindings::utils::get_array_index_from_id;
85use crate::dom::dissimilaroriginwindow::DissimilarOriginWindow;
86use crate::dom::document::Document;
87use crate::dom::element::Element;
88use crate::dom::globalscope::GlobalScope;
89use crate::dom::node::node::NodeTraits;
90use crate::dom::window::Window;
91use crate::event_loop::script_thread::{ScriptThread, with_script_thread};
92use crate::event_loop::script_window_proxies::ScriptWindowProxies;
93use crate::navigation::navigate;
94
95#[derive(Clone, Copy, PartialEq)]
96pub(crate) enum WindowOpenType {
97    ExistingOrNone,
98    NewAndUnrestricted,
99    NewWithNoOpener,
100}
101
102#[dom_struct]
103// NOTE: the browsing context for a window is managed in two places:
104// here, in script, but also in the constellation. The constellation
105// manages the session history, which in script is accessed through
106// History objects, messaging the constellation.
107pub(crate) struct WindowProxy {
108    /// The JS WindowProxy object.
109    /// Unlike other reflectors, we mutate this field because
110    /// we have to brain-transplant the reflector when the WindowProxy
111    /// changes Window.
112    reflector: Reflector,
113
114    /// The id of the browsing context.
115    /// In the case that this is a nested browsing context, this is the id
116    /// of the container.
117    #[no_trace]
118    browsing_context_id: BrowsingContextId,
119
120    // https://html.spec.whatwg.org/multipage/#opener-browsing-context
121    #[no_trace]
122    opener: Option<BrowsingContextId>,
123
124    /// The frame id of the top-level ancestor browsing context.
125    /// In the case that this is a top-level window, this is our id.
126    #[no_trace]
127    webview_id: WebViewId,
128
129    /// The name of the browsing context (sometimes, but not always,
130    /// equal to the name of a container element)
131    name: DomRefCell<TracedDOMString>,
132    /// The pipeline id of the currently active document.
133    /// May be None, when the currently active document is in another script thread.
134    /// We do not try to keep the pipeline id for documents in other threads,
135    /// as this would require the constellation notifying many script threads about
136    /// the change, which could be expensive.
137    #[no_trace]
138    currently_active: Cell<Option<PipelineId>>,
139
140    /// Has the browsing context been discarded?
141    discarded: Cell<bool>,
142
143    /// Has the browsing context been disowned?
144    disowned: Cell<bool>,
145
146    /// <https://html.spec.whatwg.org/multipage/#is-closing>
147    is_closing: Cell<bool>,
148
149    /// If the containing `<iframe>` of this [`WindowProxy`] is from a same-origin page,
150    /// this will be the [`Element`] of the `<iframe>` element in the realm of the
151    /// parent page. Otherwise, it is `None`.
152    frame_element: Option<Dom<Element>>,
153
154    /// The parent browsing context's window proxy, if this is a nested browsing context
155    parent: Option<Dom<WindowProxy>>,
156
157    /// <https://html.spec.whatwg.org/multipage/#delaying-load-events-mode>
158    delaying_load_events_mode: Cell<bool>,
159
160    /// The creator browsing context's url.
161    #[no_trace]
162    creator_url: Option<ServoUrl>,
163
164    /// The creator browsing context's origin.
165    #[no_trace]
166    creator_origin: Option<ImmutableOrigin>,
167
168    /// The window proxies the script thread knows.
169    #[conditional_malloc_size_of]
170    script_window_proxies: Rc<ScriptWindowProxies>,
171}
172
173impl WindowProxy {
174    fn new_inherited(
175        browsing_context_id: BrowsingContextId,
176        webview_id: WebViewId,
177        currently_active: Option<PipelineId>,
178        frame_element: Option<&Element>,
179        parent: Option<&WindowProxy>,
180        opener: Option<BrowsingContextId>,
181        creator: CreatorBrowsingContextInfo,
182    ) -> WindowProxy {
183        let name = frame_element.map_or(DOMString::new(), |e| {
184            e.get_string_attribute(&local_name!("name"))
185        });
186        WindowProxy {
187            reflector: Reflector::new(),
188            browsing_context_id,
189            webview_id,
190            name: DomRefCell::new(name.traced()),
191            currently_active: Cell::new(currently_active),
192            discarded: Cell::new(false),
193            disowned: Cell::new(false),
194            is_closing: Cell::new(false),
195            frame_element: frame_element.map(Dom::from_ref),
196            parent: parent.map(Dom::from_ref),
197            delaying_load_events_mode: Cell::new(false),
198            opener,
199            creator_url: creator.url,
200            creator_origin: creator.origin,
201            script_window_proxies: ScriptThread::window_proxies(),
202        }
203    }
204
205    #[expect(unsafe_code)]
206    #[expect(clippy::too_many_arguments)]
207    pub(crate) fn new(
208        cx: &mut JSContext,
209        window: &Window,
210        browsing_context_id: BrowsingContextId,
211        webview_id: WebViewId,
212        frame_element: Option<&Element>,
213        parent: Option<&WindowProxy>,
214        opener: Option<BrowsingContextId>,
215        creator: CreatorBrowsingContextInfo,
216    ) -> DomRoot<WindowProxy> {
217        unsafe {
218            let handler = window.windowproxy_handler();
219
220            let window_jsobject = window.reflector().get_jsobject();
221            assert!(!window_jsobject.get().is_null());
222            assert_ne!(
223                ((*get_object_class(window_jsobject.get())).flags & JSCLASS_IS_GLOBAL),
224                0
225            );
226
227            let mut realm = AutoRealm::new_from_handle(cx, window_jsobject);
228            let cx = &mut realm;
229
230            // Create a new window proxy.
231            rooted!(&in(cx) let js_proxy = handler.new_window_proxy(cx, window_jsobject));
232            assert!(!js_proxy.is_null());
233
234            // Create a new browsing context.
235
236            let current = Some(window.upcast::<GlobalScope>().pipeline_id());
237            let window_proxy = Box::new(WindowProxy::new_inherited(
238                browsing_context_id,
239                webview_id,
240                current,
241                frame_element,
242                parent,
243                opener,
244                creator,
245            ));
246
247            // The window proxy owns the browsing context.
248            // When we finalize the window proxy, it drops the browsing context it owns.
249            SetProxyReservedSlot(
250                js_proxy.get(),
251                0,
252                &PrivateValue(&raw const (*window_proxy) as *const libc::c_void),
253            );
254
255            // Notify the JS engine about the new window proxy binding.
256            SetWindowProxy(cx, window_jsobject, js_proxy.handle());
257
258            // Set the reflector.
259            debug!(
260                "Initializing reflector of {:p} to {:p}.",
261                window_proxy,
262                js_proxy.get()
263            );
264            window_proxy
265                .reflector
266                .init_reflector::<WindowProxy>(js_proxy.get());
267            DomRoot::from_ref(&*Box::into_raw(window_proxy))
268        }
269    }
270
271    #[expect(unsafe_code)]
272    pub(crate) fn new_dissimilar_origin(
273        cx: &mut JSContext,
274        global_to_clone_from: &GlobalScope,
275        browsing_context_id: BrowsingContextId,
276        webview_id: WebViewId,
277        parent: Option<&WindowProxy>,
278        opener: Option<BrowsingContextId>,
279        creator: CreatorBrowsingContextInfo,
280    ) -> DomRoot<WindowProxy> {
281        unsafe {
282            // Create a new browsing context.
283            let window_proxy = Box::new(WindowProxy::new_inherited(
284                browsing_context_id,
285                webview_id,
286                None,
287                None,
288                parent,
289                opener,
290                creator,
291            ));
292
293            // Create a new dissimilar-origin window.
294            let window = DissimilarOriginWindow::new(cx, global_to_clone_from, &window_proxy);
295            let window_jsobject = window.reflector().get_jsobject();
296            assert!(!window_jsobject.get().is_null());
297            assert_ne!(
298                ((*get_object_class(window_jsobject.get())).flags & JSCLASS_IS_GLOBAL),
299                0
300            );
301
302            let mut realm = AutoRealm::new_from_handle(cx, window_jsobject);
303            let cx = &mut realm;
304
305            // Create a new window proxy.
306            let handler = WindowProxyHandler::proxy_handler();
307            rooted!(&in(cx) let js_proxy = handler.new_window_proxy(cx, window_jsobject));
308            assert!(!js_proxy.is_null());
309
310            // The window proxy owns the browsing context.
311            // When we finalize the window proxy, it drops the browsing context it owns.
312            SetProxyReservedSlot(
313                js_proxy.get(),
314                0,
315                &PrivateValue(&raw const (*window_proxy) as *const libc::c_void),
316            );
317
318            // Notify the JS engine about the new window proxy binding.
319            SetWindowProxy(cx, window_jsobject, js_proxy.handle());
320
321            // Set the reflector.
322            debug!(
323                "Initializing reflector of {:p} to {:p}.",
324                window_proxy,
325                js_proxy.get()
326            );
327            window_proxy
328                .reflector
329                .init_reflector::<WindowProxy>(js_proxy.get());
330            DomRoot::from_ref(&*Box::into_raw(window_proxy))
331        }
332    }
333
334    /// <https://html.spec.whatwg.org/multipage/#creating-a-new-top-level-traversable>
335    fn creating_a_new_top_level_traversable(
336        &self,
337        cx: &mut JSContext,
338        noopener: bool,
339        name: DOMString,
340        document: &Document,
341        sandboxing_flag_set: SandboxingFlagSet,
342    ) -> Option<DomRoot<WindowProxy>> {
343        let window = document.window();
344        let (response_sender, response_receiver) = generic_channel::channel().unwrap();
345
346        let blank_url = ServoUrl::parse("about:blank").ok().unwrap();
347        let mut load_data = LoadData::new(
348            LoadOrigin::Script(document.origin().snapshot()),
349            blank_url,
350            Some(document.base_url()),
351            // This has the effect of ensuring that the new `about:blank` URL has the
352            // same origin as the `Document` that is creating the new browsing context.
353            Some(window.pipeline_id()),
354            document.global().get_referrer(),
355            document.get_referrer_policy(),
356            None, // Doesn't inherit secure context
357            None,
358            HashSet::new(),
359            false,
360            sandboxing_flag_set,
361        );
362        load_data.is_initial_about_blank = true;
363        let load_info = AuxiliaryWebViewCreationRequest {
364            load_data: load_data.clone(),
365            opener_webview_id: window.webview_id(),
366            opener_pipeline_id: self.currently_active.get().unwrap(),
367            response_sender,
368        };
369        let constellation_msg = ScriptToConstellationMessage::CreateAuxiliaryWebView(load_info);
370        window.send_to_constellation(constellation_msg);
371
372        let response = response_receiver.recv().unwrap()?;
373        let new_browsing_context_id = BrowsingContextId::from(response.new_webview_id);
374        let new_pipeline_info = NewPipelineInfo {
375            webview_state: WebViewState {
376                id: response.new_webview_id,
377                // Use the current `WebView`'s theme initially, but the embedder may change
378                // this later.
379                theme: Cell::new(window.webview_theme()),
380                // WebViews start focused by default for now.
381                has_system_focus: Cell::new(true),
382            },
383            parent_info: None,
384            new_pipeline_id: response.new_pipeline_id,
385            browsing_context_id: new_browsing_context_id,
386            opener: Some(self.browsing_context_id),
387            load_data,
388            viewport_details: window.viewport_details(),
389            user_content_manager_id: response.user_content_manager_id,
390            target_snapshot_params: TargetSnapshotParams {
391                sandboxing_flags: sandboxing_flag_set,
392                iframe_element_referrer_policy: ReferrerPolicy::EmptyString,
393            },
394            frame_name: None,
395        };
396
397        with_script_thread(|script_thread| {
398            script_thread.spawn_pipeline(cx, new_pipeline_info);
399        });
400
401        let new_window_proxy = ScriptThread::find_document(response.new_pipeline_id)
402            .and_then(|doc| doc.browsing_context())?;
403        if !name.eq_ignore_ascii_case("_blank") {
404            new_window_proxy.set_name(name);
405        }
406        // Step 2. If opener is null, then set document to the second return value
407        // of creating a new top-level browsing context and document.
408        if noopener {
409            new_window_proxy.disown();
410        } else {
411            // After creating a new auxiliary browsing context and document,
412            // the session storage is copied over.
413            // See https://html.spec.whatwg.org/multipage/#the-sessionstorage-attribute
414
415            let (sender, receiver) = generic_channel::channel().unwrap();
416
417            let msg = WebStorageThreadMsg::Clone {
418                sender,
419                src: window.window_proxy().webview_id(),
420                dest: response.new_webview_id,
421            };
422
423            GenericSend::send(document.global().storage_threads(), msg).unwrap();
424            receiver.recv().unwrap();
425        }
426        // Step 13. Return traversable.
427        Some(new_window_proxy)
428    }
429
430    /// <https://html.spec.whatwg.org/multipage/#delaying-load-events-mode>
431    pub(crate) fn start_delaying_load_events_mode(&self) {
432        self.delaying_load_events_mode.set(true);
433    }
434
435    /// <https://html.spec.whatwg.org/multipage/#delaying-load-events-mode>
436    pub(crate) fn stop_delaying_load_events_mode(&self) {
437        self.delaying_load_events_mode.set(false);
438    }
439
440    /// <https://html.spec.whatwg.org/multipage/#disowned-its-opener>
441    pub(crate) fn disown(&self) {
442        self.disowned.set(true);
443    }
444
445    /// <https://html.spec.whatwg.org/multipage/#dom-window-close>
446    /// Step 3.1, set BCs `is_closing` to true.
447    pub(crate) fn close(&self) {
448        self.is_closing.set(true);
449    }
450
451    /// <https://html.spec.whatwg.org/multipage/#is-closing>
452    pub(crate) fn is_closing(&self) -> bool {
453        self.is_closing.get()
454    }
455
456    /// <https://html.spec.whatwg.org/multipage/#dom-opener>
457    pub(crate) fn opener(&self, cx: &mut CurrentRealm, mut retval: MutableHandleValue) {
458        if self.disowned.get() {
459            return retval.set(NullValue());
460        }
461        let opener_id = match self.opener {
462            Some(opener_browsing_context_id) => opener_browsing_context_id,
463            None => return retval.set(NullValue()),
464        };
465        let parent_browsing_context = self.parent.as_deref();
466        let opener_proxy = match self.script_window_proxies.find_window_proxy(opener_id) {
467            Some(window_proxy) => window_proxy,
468            None => {
469                let sender_pipeline_id = self.currently_active().unwrap();
470                match ScriptThread::get_top_level_for_browsing_context(
471                    self.webview_id(),
472                    sender_pipeline_id,
473                    opener_id,
474                ) {
475                    Some(opener_top_id) => {
476                        let global_to_clone_from = GlobalScope::from_current_realm(cx);
477                        let creator =
478                            CreatorBrowsingContextInfo::from(parent_browsing_context, None);
479                        WindowProxy::new_dissimilar_origin(
480                            cx,
481                            &global_to_clone_from,
482                            opener_id,
483                            opener_top_id,
484                            None,
485                            None,
486                            creator,
487                        )
488                    },
489                    None => return retval.set(NullValue()),
490                }
491            },
492        };
493        if opener_proxy.is_browsing_context_discarded() {
494            return retval.set(NullValue());
495        }
496        opener_proxy.to_jsval(cx, retval);
497    }
498
499    /// <https://html.spec.whatwg.org/multipage/#window-open-steps>
500    pub(crate) fn open(
501        &self,
502        cx: &mut JSContext,
503        url: USVString,
504        target: DOMString,
505        features: DOMString,
506    ) -> Fallible<Option<DomRoot<WindowProxy>>> {
507        // Note: this does not map to the spec,
508        // but it does prevent a panic at the constellation because the browsing context
509        // has already been discarded.
510        // See issue: #39716 for the original problem,
511        // and https://github.com/whatwg/html/issues/11797 for a discussion at the level of the spec.
512        if self.discarded.get() {
513            return Ok(None);
514        }
515        // Step 2. Let sourceDocument be the entry global object's associated Document.
516        //
517        // It's possible to end up in a situation where JS code is executing but
518        // we have not had a chance to push an entry global (e.g. via WASM instantiation).
519        // If that happens, fall back to the active document of this browsing context.
520        let source_document = maybe_entry_global()
521            .map(|global| global.as_window().Document())
522            .or_else(|| self.document())
523            .expect("Must have an entry global or active document");
524        // Step 4. If url is not the empty string:
525        let url_record = if !url.is_empty() {
526            // Step 4.1. Set urlRecord to the result of encoding-parsing a URL given url, relative to sourceDocument.
527            let Ok(url) = source_document.encoding_parse_a_url(&url) else {
528                // Step 4.2. If urlRecord is failure, then throw a "SyntaxError" DOMException.
529                return Err(Error::Syntax(Some(format!(
530                    "Error parsing URL '{url}' relative to '{}'",
531                    source_document.url()
532                ))));
533            };
534            Some(url)
535        } else {
536            // Step 3. Let urlRecord be null.
537            None
538        };
539        // Step 5. If target is the empty string, then set target to "_blank".
540        let non_empty_target = if target.is_empty() {
541            DOMString::from_static("_blank")
542        } else {
543            target
544        };
545        // Step 6. Let tokenizedFeatures be the result of tokenizing features.
546        let tokenized_features = tokenize_open_features(features);
547        // Step 7. Let noreferrer be false.
548        // Step 8. If tokenizedFeatures["noreferrer"] exists,
549        // then set noreferrer to the result of parsing tokenizedFeatures["noreferrer"] as a boolean feature.
550        let noreferrer = parse_open_feature_boolean(&tokenized_features, "noreferrer");
551
552        // Step 12. If noreferrer is true, then set noopener to true
553        // and set referrerPolicy to "no-referrer".
554        let (noopener, referrer_policy) = if noreferrer {
555            (true, ReferrerPolicy::NoReferrer)
556        } else {
557            // Step 9. Let noopener be the result of getting noopener for window open with sourceDocument,
558            // tokenizedFeatures, and urlRecord.
559            // Step 11. Let referrerPolicy be the empty string.
560            (
561                parse_open_feature_boolean(&tokenized_features, "noopener"),
562                ReferrerPolicy::EmptyString,
563            )
564        };
565        // (TODO) Step 10. Remove tokenizedFeatures["noopener"] and tokenizedFeatures["noreferrer"].
566
567        // Step 13. Let targetNavigable and windowType be the result of applying the rules for
568        // choosing a navigable given target, sourceDocument's node navigable, and noopener.
569        let (chosen, window_type) = match self.choose_a_navigable(cx, &non_empty_target, noopener) {
570            (Some(chosen), window_type) => (chosen, window_type),
571            // Step 14. If targetNavigable is null, then return null.
572            (None, _) => return Ok(None),
573        };
574        let target_document = match chosen.document() {
575            Some(target_document) => target_document,
576            None => return Ok(None),
577        };
578        let target_window = target_document.window();
579        let referrer = if noreferrer {
580            Referrer::NoReferrer
581        } else {
582            target_window.as_global_scope().get_referrer()
583        };
584
585        // Step 15. If windowType is either "new and unrestricted" or "new with no opener":
586        if matches!(
587            window_type,
588            WindowOpenType::NewAndUnrestricted | WindowOpenType::NewWithNoOpener
589        ) {
590            // Step 15.1. Set targetNavigable's active browsing context's is popup to
591            // the result of checking if a popup window is requested, given tokenizedFeatures.
592            // TODO
593
594            // TODO Step 15.2, Set up browsing context features for targetNavigable's
595            // active browsing context given tokenizedFeatures.
596            let has_trustworthy_ancestor_origin = if window_type != WindowOpenType::ExistingOrNone {
597                target_document.has_trustworthy_ancestor_or_current_origin()
598            } else {
599                false
600            };
601            // Step 15.3. If urlRecord is null, then set urlRecord to a URL record representing about:blank.
602            let url_record = url_record.unwrap_or(ServoUrl::parse("about:blank").unwrap());
603            // Step 15.4. If urlRecord matches about:blank,
604            // then perform the URL and history update steps given targetNavigable's active document and urlRecord.
605            //
606            // This happened in the constellation as part of creating the auxiliary browsing context.
607            if !url_record.matches_about_blank() {
608                // Propagate CSP list and about-base-url from opener to new document
609                let csp_list = source_document.get_csp_list().clone();
610                target_document.set_csp_list(csp_list);
611
612                // Step 15.5 Otherwise, navigate targetNavigable to urlRecord using sourceDocument,
613                // with referrerPolicy set to referrerPolicy and exceptionsEnabled set to true.
614                // FIXME: exceptionsEnabled not used.
615                let mut load_data =
616                    target_window.load_data_for_document(url_record, source_document.pipeline_id());
617                load_data.referrer = referrer;
618                load_data.referrer_policy = referrer_policy;
619                load_data.has_trustworthy_ancestor_origin = has_trustworthy_ancestor_origin;
620
621                navigate(
622                    cx,
623                    target_window,
624                    NavigationHistoryBehavior::Replace,
625                    false,
626                    load_data,
627                );
628            }
629        } else {
630            // Step 16. Otherwise:
631            // Step 16.1. If urlRecord is not null, then navigate targetNavigable
632            // to urlRecord using sourceDocument, with referrerPolicy set to referrerPolicy
633            // and exceptionsEnabled set to true.
634            if let Some(url_record) = url_record {
635                let mut load_data =
636                    target_window.load_data_for_document(url_record, target_window.pipeline_id());
637                load_data.referrer = referrer;
638                load_data.referrer_policy = referrer_policy;
639                navigate(
640                    cx,
641                    target_window,
642                    NavigationHistoryBehavior::Push,
643                    false,
644                    load_data,
645                );
646            }
647        }
648
649        // Step 17. If windowType is "new with no opener", then return null.
650        if window_type == WindowOpenType::NewWithNoOpener {
651            return Ok(None);
652        }
653        // Step 18. If noopener is true and target is not an ASCII case-insensitive match
654        // for "_self", "_parent", or "_top", then return null.
655        if noopener &&
656            !(non_empty_target.eq_ignore_ascii_case("_self") ||
657                non_empty_target.eq_ignore_ascii_case("_parent") ||
658                non_empty_target.eq_ignore_ascii_case("_top"))
659        {
660            return Ok(None);
661        }
662
663        // Step 19. Return targetNavigable's active WindowProxy.
664        Ok(target_document.browsing_context())
665    }
666
667    /// <https://html.spec.whatwg.org/multipage/#the-rules-for-choosing-a-navigable>
668    pub(crate) fn choose_a_navigable(
669        &self,
670        cx: &mut JSContext,
671        name: &DOMString,
672        noopener: bool,
673    ) -> (Option<DomRoot<WindowProxy>>, WindowOpenType) {
674        // Step 3. Let sandboxingFlagSet be currentNavigable's active document's active
675        // sandboxing flag set.
676        let sandboxing_flag_set = self
677            .document()
678            .map(|document| document.active_sandboxing_flag_set())
679            .unwrap_or_default();
680
681        let chosen = if name.is_empty() || name.eq_ignore_ascii_case("_self") {
682            // Step 4. If name is the empty string or an ASCII case-insensitive match for
683            // "_self", then set chosen to currentNavigable.
684            Some(DomRoot::from_ref(self))
685        } else if name.eq_ignore_ascii_case("_parent") {
686            // Step 5. Otherwise, if name is an ASCII case-insensitive match for
687            // "_parent", set chosen to currentNavigable's parent, if any, and
688            // currentNavigable otherwise.
689            Some(
690                self.parent()
691                    .map_or_else(|| DomRoot::from_ref(self), DomRoot::from_ref),
692            )
693        } else if name.eq_ignore_ascii_case("_top") {
694            // Step 6. Otherwise, if name is an ASCII case-insensitive match for "_top",
695            // set chosen to currentNavigable's traversable navigable.
696            Some(DomRoot::from_ref(self.top()))
697        } else if !name.eq_ignore_ascii_case("_blank") {
698            // Step 7. Otherwise, if name is not an ASCII case-insensitive match for
699            // "_blank" and noopener is false, then set chosen to the result of finding a
700            // navigable by target name given name and currentNavigable.
701            //
702            // Note: The noopener==false condition here seems to break WPT tests and
703            // is likely a specification bug.
704            // See <https://github.com/whatwg/html/issues/12839>
705            self.find_navigable_by_target_name(name)
706        } else {
707            // Step 1. Let chosen be null.
708            None
709        };
710
711        // Step 9. Return chosen and windowType.
712        //
713        // Early-return here to save indentation on all the other steps
714        if let Some(chosen) = chosen {
715            // Step 2. Let windowType be "existing or none".
716            return (Some(chosen), WindowOpenType::ExistingOrNone);
717        }
718
719        // Step 8. If chosen is null, then a new top-level traversable is being requested,
720        // and what happens depends on the user agent's configuration and abilities — it
721        // is determined by the rules given for the first applicable option from the
722        // following list:
723        //
724        // ↪ If currentNavigable's active window does not have transient
725        //   activation and the user agent has been configured to not show popups
726        //   (i.e., the user agent has a "popup blocker" enabled)
727        //    - The user agent may inform the user that a popup has been blocked.
728        // TODO: Implement this.
729        //
730        // ↪ If sandboxingFlagSet has the sandboxed auxiliary navigation browsing context flag set
731        //   - The user agent may report to a developer console that a popup has been blocked.
732        if sandboxing_flag_set
733            .contains(SandboxingFlagSet::SANDBOXED_AUXILIARY_NAVIGATION_BROWSING_CONTEXT_FLAG)
734        {
735            return (None, WindowOpenType::ExistingOrNone);
736        }
737        // ↪ If the user agent has been configured such that in this instance it
738        // will create a new top-level traversable
739
740        // Substep 2. Set windowType to "new and unrestricted".
741        let mut window_type = WindowOpenType::NewAndUnrestricted;
742
743        // Substep 3. Let currentDocument be currentNavigable's active document.
744        let current_document = self
745            .currently_active
746            .get()
747            .and_then(ScriptThread::find_document)
748            .unwrap();
749
750        // Substep 1. Consume user activation of currentNavigable's active window.
751        current_document.window().consume_user_activation();
752
753        // Substep 4. If currentDocument's opener policy's value is "same-origin" or "same-origin-plus-COEP",
754        // and currentDocument's origin is not same origin with currentDocument's
755        // relevant settings object's top-level origin:
756        // TODO
757
758        // Substep 6. If name is not an ASCII case-insensitive match for "_blank", then set targetName to name.
759        let target_name = if !name.eq_ignore_ascii_case("_blank") {
760            name.clone()
761        } else {
762            // Substep 5. Let targetName be the empty string.
763            Default::default()
764        };
765
766        // Substep 9. If sandboxingFlagSet's sandbox propagates to auxiliary browsing contexts flag is set,
767        // then all the flags that are set in sandboxingFlagSet must be set in chosen's
768        // active browsing context's popup sandboxing flag set.
769        //
770        // We do this step first so we can pass it to LoadData
771        let sandboxing_flag_set = current_document.active_sandboxing_flag_set();
772        let propagate_sandbox = sandboxing_flag_set
773            .contains(SandboxingFlagSet::SANDBOX_PROPOGATES_TO_AUXILIARY_BROWSING_CONTEXTS_FLAG);
774        let sandboxing_flag_set = if propagate_sandbox {
775            sandboxing_flag_set
776        } else {
777            SandboxingFlagSet::empty()
778        };
779
780        // Substep 7. If noopener is true:
781        let chosen = if noopener {
782            // Substep 7.1. Set windowType to "new with no opener"
783            window_type = WindowOpenType::NewWithNoOpener;
784
785            // Substep 7.2. Set chosen to the result of creating a new top-level traversable
786            // given null, targetName, and currentNavigable.
787            // TODO: pass `null` here instead
788            self.creating_a_new_top_level_traversable(
789                cx,
790                true,
791                target_name,
792                &current_document,
793                sandboxing_flag_set,
794            )
795        } else {
796            // Substep 8. Otherwise:
797            // Substep 8.1. Set chosen to the result of creating a new top-level traversable given
798            // currentNavigable's active browsing context, targetName, and currentNavigable.
799            // TODO: instead of the boolean, pass the browsing context here
800            self.creating_a_new_top_level_traversable(
801                cx,
802                false,
803                target_name,
804                &current_document,
805                sandboxing_flag_set,
806            )
807
808            // Substep 8.2. If sandboxingFlagSet's sandboxed navigation browsing context flag is set,
809            // then set chosen's active browsing context's one permitted sandboxed navigator
810            // to currentNavigable's active browsing context.
811            // TODO
812        };
813
814        // Substep 10. Set chosen's is created by web content to true.
815        // TODO
816
817        // Step 9. Return chosen and windowType.
818        (chosen, window_type)
819    }
820
821    /// <https://html.spec.whatwg.org/multipage/#find-a-navigable-by-target-name>
822    fn find_navigable_by_target_name(&self, name: &DOMString) -> Option<DomRoot<WindowProxy>> {
823        // Step 1. Let currentDocument be currentNavigable's active document.
824        //
825        // Step 2. Let sourceSnapshotParams be the result of snapshotting source snapshot
826        // params given currentDocument.
827        // TODO: This is unimplemented.
828        //
829        // Step 3. Let subtreesToSearch be an implementation-defined choice of one of the
830        // following:
831        //     - « currentNavigable's traversable navigable, currentNavigable »
832        //     - the inclusive ancestor navigables of currentDocument
833        //
834        // From <https://github.com/whatwg/html/issues/10848>:
835        // > WebKit and Chromium search the requesting window's subtree then search from
836        // > the top. Firefox iterates and searches from each ancestor. If there's a way to
837        // > express in the spec that the implementation-defined behavior is fixed for the
838        // > instance of the user agent, then that'd be appropriate here.
839        //
840        // We use the Webkit and Chrome approach here and the reversal is done here
841        // rather than below.
842        let top = self.top();
843        let subtrees_to_search = if top != self {
844            Either::Left([self, top])
845        } else {
846            Either::Right([self])
847        };
848
849        // Step 4. For each subtreeToSearch of subtreesToSearch, in reverse order:
850        for subtree_to_search in subtrees_to_search.into_iter() {
851            // Step 4.1. Let documentToSearch be subtreeToSearch's active document.
852            // Step 4.2. For each navigable of the inclusive descendant navigables of
853            // documentToSearch:
854            if let Some(result) =
855                subtree_to_search.find_navigable_by_target_name_in_descendants(name)
856            {
857                return Some(result);
858            }
859        }
860
861        // Step 5. Let currentTopLevelBrowsingContext be currentNavigable's active
862        // browsing context's top-level browsing context.
863        // Step 6. Let group be currentTopLevelBrowsingContext's group.
864        //
865        // TODO: Servo doesn't have a concept of the browsing context group in script, so
866        // we just look through all top-level WindowProxy instances.
867        let mut top_level_window_proxies = self.script_window_proxies.top_level_window_proxies();
868
869        // Step 7. For each topLevelBrowsingContext of group's browsing context set, in an
870        // implementation-defined order (the user agent should pick a consistent ordering,
871        // such as the most recently opened, most recently focused, or more closely
872        // related):
873        //
874        // Sorting by `BrowsingContextId` is an attempt to make the order consistent.
875        // This also ensures that newer `BrowsingContextId`s are sorted first.
876        top_level_window_proxies
877            .sort_by_key(|proxy| std::cmp::Reverse(proxy.browsing_context_id()));
878
879        for window_proxy in top_level_window_proxies {
880            // Step 7.1. If currentTopLevelBrowsingContext is topLevelBrowsingContext, then
881            // continue.
882            if &*window_proxy == top {
883                continue;
884            }
885            // Step 7.2. Let documentToSearch be topLevelBrowsingContext's active document.
886            // Step 7.3. For each navigable of the inclusive descendant navigables of
887            // documentToSearch:
888            //
889            // Step 7.3.1 If currentNavigable's active browsing context is not familiar
890            // with navigable's active browsing context, then continue.
891            //
892            // TODO: Servo does not implement the concept of "familiar with".
893            // See: <https://html.spec.whatwg.org/multipage/#familiar-with>
894            // TODO: Properly support navigables in other script threads and with
895            // dissimilar origins, which requires that they be accessible here and
896            // WindowProxy::get_name() returns something useful.
897            //
898            // Step 7.3.2. If currentNavigable is not allowed by sandboxing to navigate
899            // navigable given sourceSnapshotParams, then optionally continue.
900            // Step 7.3.3 If navigable's target name is name, then return navigable.
901            // These steps are handled by `find_navigable_by_target_name_in_descendants`.
902            if let Some(result) = window_proxy.find_navigable_by_target_name_in_descendants(name) {
903                return Some(result);
904            }
905        }
906
907        // Step 8. Return null.
908        None
909    }
910
911    /// <https://html.spec.whatwg.org/multipage/#find-a-navigable-by-target-name> step 4 and 7 substeps.
912    fn find_navigable_by_target_name_in_descendants(
913        &self,
914        name: &DOMString,
915    ) -> Option<DomRoot<WindowProxy>> {
916        // Never traverse or return a `WindowProxy` with a discarded browsing context.
917        if self.is_browsing_context_discarded() {
918            return None;
919        }
920
921        // Step 4.2.1 If currentNavigable is not allowed by sandboxing to navigate
922        // navigable given sourceSnapshotParams, then optionally continue.
923        // TODO: This is unimplemented.
924
925        // Step 4.2.2. If navigable's target name is name, then return navigable.
926        if self.get_name() == *name {
927            return Some(DomRoot::from_ref(self));
928        }
929
930        let document = self.document()?;
931        let iframes: Vec<_> = document.iframes().iter().collect();
932        iframes.iter().find_map(|iframe| {
933            iframe
934                .browsing_context_id()
935                .and_then(|browsing_context_id| {
936                    self.script_window_proxies
937                        .find_window_proxy(browsing_context_id)?
938                        .find_navigable_by_target_name_in_descendants(name)
939                })
940        })
941    }
942
943    pub(crate) fn is_auxiliary(&self) -> bool {
944        self.opener.is_some()
945    }
946
947    pub(crate) fn discard_browsing_context(&self) {
948        self.discarded.set(true);
949    }
950
951    pub(crate) fn is_browsing_context_discarded(&self) -> bool {
952        self.discarded.get()
953    }
954
955    pub(crate) fn browsing_context_id(&self) -> BrowsingContextId {
956        self.browsing_context_id
957    }
958
959    pub(crate) fn webview_id(&self) -> WebViewId {
960        self.webview_id
961    }
962
963    /// If the containing `<iframe>` of this [`WindowProxy`] is from a same-origin page,
964    /// this will return an [`Element`] of the `<iframe>` element in the realm of the parent
965    /// page.
966    ///
967    /// This returns `None` if the browsing context for this [`WindowProxy`]
968    /// has been discarded.
969    pub(crate) fn frame_element(&self) -> Option<&Element> {
970        if self.is_browsing_context_discarded() {
971            return None;
972        }
973        self.frame_element.as_deref()
974    }
975
976    pub(crate) fn document(&self) -> Option<DomRoot<Document>> {
977        self.currently_active
978            .get()
979            .and_then(ScriptThread::find_document)
980    }
981
982    pub(crate) fn parent(&self) -> Option<&WindowProxy> {
983        self.parent.as_deref()
984    }
985
986    pub(crate) fn top(&self) -> &WindowProxy {
987        let mut result = self;
988        while let Some(parent) = result.parent() {
989            result = parent;
990        }
991        result
992    }
993
994    pub(crate) fn document_origin_and_internal_ancestor_origin_objects_list(
995        &self,
996    ) -> Option<(OriginSnapshot, Vec<ImmutableOrigin>)> {
997        let pipeline_id = self.currently_active()?;
998        let (result_sender, result_receiver) = generic_channel::channel().unwrap();
999        self.global()
1000            .script_to_constellation_chan()
1001            .send(ScriptToConstellationMessage::GetDocumentOriginDetails(
1002                pipeline_id,
1003                result_sender,
1004            ))
1005            .ok()?;
1006        result_receiver.recv().ok()?
1007    }
1008
1009    /// <https://html.spec.whatwg.org/multipage/#internal-ancestor-origin-objects-list-creation-steps>
1010    pub(crate) fn parent_origin_and_internal_ancestor_origin_objects_list(
1011        &self,
1012    ) -> Option<(OriginSnapshot, Vec<ImmutableOrigin>)> {
1013        if let Some(frame_element) = self.frame_element() {
1014            let parent_document = frame_element.owner_document();
1015            // Step 4. Assert: parentDoc is fully active.
1016            // TODO(47417): Once "creating a new browsing context" properly exists, remove this check
1017            if !parent_document.is_fully_active() {
1018                return None;
1019            }
1020            Some((
1021                parent_document.origin().snapshot(),
1022                parent_document
1023                    .internal_ancestor_origin_objects_list()
1024                    .clone()
1025                    .expect("Must always be fully active"),
1026            ))
1027        } else if let Some(parent_proxy) = self.parent() {
1028            // Step 4. Assert: parentDoc is fully active.
1029            assert!(parent_proxy.currently_active().is_some());
1030            parent_proxy.document_origin_and_internal_ancestor_origin_objects_list()
1031        } else {
1032            None
1033        }
1034    }
1035
1036    #[expect(unsafe_code)]
1037    /// Change the Window that this WindowProxy resolves to.
1038    // TODO: support setting the window proxy to a dummy value,
1039    // to handle the case when the active document is in another script thread.
1040    fn set_window(&self, cx: &mut JSContext, window: &GlobalScope) {
1041        unsafe {
1042            debug!("Setting window of {:p}.", self);
1043
1044            let window_jsobject = window.reflector().get_jsobject();
1045            let old_js_proxy = self.reflector.get_jsobject();
1046            assert!(!window_jsobject.get().is_null());
1047            assert_ne!(
1048                ((*get_object_class(window_jsobject.get())).flags & JSCLASS_IS_GLOBAL),
1049                0
1050            );
1051
1052            let mut realm = AutoRealm::new_from_handle(cx, window_jsobject);
1053            let cx = &mut realm;
1054
1055            // The old window proxy no longer owns this browsing context.
1056            SetProxyReservedSlot(old_js_proxy.get(), 0, &PrivateValue(ptr::null_mut()));
1057            // Also drop any cached cross-origin property holders.
1058            SetProxyReservedSlot(
1059                old_js_proxy.get(),
1060                CROSS_ORIGIN_PROPERTY_HOLDER_WEAK_MAP_SLOT,
1061                &UndefinedValue(),
1062            );
1063
1064            // Brain transplant the window proxy. Brain transplantation is
1065            // usually done to move a window proxy between compartments, but
1066            // that's not what we are doing here. We need to do this to retarget
1067            // the proxy at a different global without updating its identity.
1068            rooted!(&in(cx) let new_js_proxy = WindowProxyHandler::proxy_handler().new_window_proxy(cx, window_jsobject));
1069            // Explicitly set this slot to a null pointer in case a GC occurs before we
1070            // are ready to set it to a real value.
1071            SetProxyReservedSlot(new_js_proxy.get(), 0, &PrivateValue(ptr::null_mut()));
1072            debug!(
1073                "Transplanting proxy from {:p} to {:p}.",
1074                old_js_proxy.get(),
1075                new_js_proxy.get()
1076            );
1077            rooted!(&in(cx) let new_js_proxy = JS_TransplantObject(cx, old_js_proxy, new_js_proxy.handle()));
1078            debug!("Transplanted proxy is {:p}.", new_js_proxy.get());
1079
1080            // Transfer ownership of this browsing context from the old window proxy to the new one.
1081            SetProxyReservedSlot(
1082                new_js_proxy.get(),
1083                0,
1084                &PrivateValue(self as *const _ as *const libc::c_void),
1085            );
1086
1087            // Notify the JS engine about the new window proxy binding.
1088            SetWindowProxy(cx, window_jsobject, new_js_proxy.handle());
1089
1090            // Update the reflector.
1091            debug!(
1092                "Setting reflector of {:p} to {:p}.",
1093                self,
1094                new_js_proxy.get()
1095            );
1096            self.reflector.rootable().set(new_js_proxy.get());
1097        }
1098    }
1099
1100    pub(crate) fn set_pipeline_id(&self, pipeline_id: PipelineId) {
1101        self.currently_active.set(Some(pipeline_id));
1102    }
1103
1104    pub(crate) fn set_currently_active(&self, cx: &mut JSContext, window: &Window) {
1105        if let Some(pipeline_id) = self.currently_active() &&
1106            pipeline_id == window.pipeline_id()
1107        {
1108            return debug!(
1109                "Attempt to set the currently active window to the currently active window."
1110            );
1111        }
1112
1113        let global_scope = window.as_global_scope();
1114        self.set_window(cx, global_scope);
1115        self.currently_active.set(Some(global_scope.pipeline_id()));
1116    }
1117
1118    pub(crate) fn unset_currently_active(&self, cx: &mut JSContext) {
1119        if self.currently_active().is_none() {
1120            return debug!(
1121                "Attempt to unset the currently active window on a windowproxy that does not have one."
1122            );
1123        }
1124        let globalscope = self.global();
1125        let window = DissimilarOriginWindow::new(cx, &globalscope, self);
1126        self.set_window(cx, window.upcast());
1127        self.currently_active.set(None);
1128    }
1129
1130    pub(crate) fn currently_active(&self) -> Option<PipelineId> {
1131        self.currently_active.get()
1132    }
1133
1134    pub(crate) fn get_name(&self) -> DOMString {
1135        self.name.borrow().clone().root()
1136    }
1137
1138    pub(crate) fn set_name(&self, name: DOMString) {
1139        *self.name.borrow_mut() = name.traced();
1140    }
1141}
1142
1143/// A browsing context can have a creator browsing context, the browsing context that
1144/// was responsible for its creation. If a browsing context has a parent browsing context,
1145/// then that is its creator browsing context. Otherwise, if the browsing context has an
1146/// opener browsing context, then that is its creator browsing context. Otherwise, the
1147/// browsing context has no creator browsing context.
1148///
1149/// If a browsing context A has a creator browsing context, then the Document that was the
1150/// active document of that creator browsing context at the time A was created is the creator
1151/// Document.
1152///
1153/// See: <https://html.spec.whatwg.org/multipage/#creating-browsing-contexts>
1154#[derive(Debug, Deserialize, Serialize)]
1155pub(crate) struct CreatorBrowsingContextInfo {
1156    /// Creator document URL.
1157    url: Option<ServoUrl>,
1158
1159    /// Creator document origin.
1160    origin: Option<ImmutableOrigin>,
1161}
1162
1163impl CreatorBrowsingContextInfo {
1164    pub(crate) fn from(
1165        parent: Option<&WindowProxy>,
1166        opener: Option<&WindowProxy>,
1167    ) -> CreatorBrowsingContextInfo {
1168        let creator = match (parent, opener) {
1169            (Some(parent), _) => parent.document(),
1170            (None, Some(opener)) => opener.document(),
1171            (None, None) => None,
1172        };
1173
1174        let url = creator.as_deref().map(|document| document.url());
1175        let origin = creator
1176            .as_deref()
1177            .map(|document| document.origin().immutable().clone());
1178
1179        CreatorBrowsingContextInfo { url, origin }
1180    }
1181}
1182
1183/// <https://html.spec.whatwg.org/multipage/#concept-window-open-features-tokenize>
1184fn tokenize_open_features(features: DOMString) -> IndexMap<String, String> {
1185    let is_feature_sep = |c: char| c.is_ascii_whitespace() || ['=', ','].contains(&c);
1186    // Step 1. Let tokenizedFeatures be a new ordered map.
1187    let mut tokenized_features = IndexMap::new();
1188    // Step 2. Let position point at the first code point of features.
1189    let features = features.str();
1190    let mut iter = features.chars();
1191    let mut cur = iter.next();
1192
1193    // Step 3. While position is not past the end of features:
1194    while cur.is_some() {
1195        // Step 3.1. Let name be the empty string.
1196        // Step 3.2. Let value be the empty string.
1197        let mut name = String::new();
1198        let mut value = String::new();
1199        // Step 3.3. Collect a sequence of code points that are feature separators
1200        // from features given position. This skips past leading separators before the name.
1201        while let Some(cur_char) = cur {
1202            if !is_feature_sep(cur_char) {
1203                break;
1204            }
1205            cur = iter.next();
1206        }
1207        // Step 3.4. Collect a sequence of code points that are not feature separators
1208        // from features given position. Set name to the collected characters, converted to ASCII lowercase.
1209        while let Some(cur_char) = cur {
1210            if is_feature_sep(cur_char) {
1211                break;
1212            }
1213            name.push(cur_char.to_ascii_lowercase());
1214            cur = iter.next();
1215        }
1216        // Step 3.5. Set name to the result of normalizing the feature name name.
1217        let normalized_name = String::from(match name.as_ref() {
1218            "screenx" => "left",
1219            "screeny" => "top",
1220            "innerwidth" => "width",
1221            "innerheight" => "height",
1222            _ => name.as_ref(),
1223        });
1224        // Step 3.6. While position is not past the end of features
1225        // and the code point at position in features is not U+003D (=):
1226        while let Some(cur_char) = cur &&
1227            cur_char != '='
1228        {
1229            // Step 3.6.1. If the code point at position in features is U+002C (,),
1230            // or if it is not a feature separator, then break.
1231            if cur_char == ',' || !is_feature_sep(cur_char) {
1232                break;
1233            }
1234            // Step 3.6.2. Advance position by 1.
1235            cur = iter.next();
1236        }
1237        // Step 3.7. If the code point at position in features is a feature separator:
1238        if cur.is_some() && is_feature_sep(cur.unwrap()) {
1239            // Step 3.7.1. While position is not past the end of features and
1240            // the code point at position in features is a feature separator:
1241            while let Some(cur_char) = cur &&
1242                is_feature_sep(cur_char)
1243            {
1244                // Step 3.7.1.1. If the code point at position in features is U+002C (,), then break.
1245                if cur_char == ',' {
1246                    break;
1247                }
1248                // Step 3.7.1.2. Advance position by 1.
1249                cur = iter.next();
1250            }
1251            // Step 3.7.2. Collect a sequence of code points that are not feature separators
1252            // code points from features given position.
1253            // Set value to the collected code points, converted to ASCII lowercase.
1254            while let Some(cur_char) = cur {
1255                if is_feature_sep(cur_char) {
1256                    break;
1257                }
1258                value.push(cur_char.to_ascii_lowercase());
1259                cur = iter.next();
1260            }
1261        }
1262        // Step 3.8. If name is not the empty string, then set tokenizedFeatures[name] to value.
1263        if !name.is_empty() {
1264            tokenized_features.insert(normalized_name, value);
1265        }
1266    }
1267    // Step 4. Return tokenizedFeatures.
1268    tokenized_features
1269}
1270
1271/// <https://html.spec.whatwg.org/multipage/#concept-window-open-features-parse-boolean>
1272fn parse_open_feature_boolean(tokenized_features: &IndexMap<String, String>, name: &str) -> bool {
1273    if let Some(value) = tokenized_features.get(name) {
1274        // Step 1 & 2
1275        if value.is_empty() || value == "yes" {
1276            return true;
1277        }
1278        // Step 3 & 4
1279        if let Ok(int) = parse_integer(value.chars()) {
1280            return int != 0;
1281        }
1282    }
1283    // Step 5
1284    false
1285}
1286
1287#[expect(unsafe_code)]
1288fn window_proxy_target(proxy: HandleObject) -> *mut JSObject {
1289    let mut slot = UndefinedValue();
1290    unsafe { GetProxyPrivate(proxy.as_raw(), &mut slot) };
1291    slot.to_object()
1292}
1293
1294/// <https://html.spec.whatwg.org/multipage/#windowproxy-getownproperty>
1295#[expect(unsafe_code)]
1296unsafe extern "C" fn get_own_property_descriptor(
1297    cx: *mut RawJSContext,
1298    proxy: RawHandleObject,
1299    id: RawHandleId,
1300    property_descriptor: RawMutableHandle<PropertyDescriptor>,
1301    is_none: *mut bool,
1302) -> bool {
1303    let mut cx = unsafe {
1304        // SAFETY: We are in a SpiderMonkey hook, so it is always safe to convert a raw context into
1305        // a mozjs context.
1306        JSContext::from_ptr(NonNull::new(cx).expect("JSContext should not be null in SM hook"))
1307    };
1308    let mut cx = CurrentRealm::assert(&mut cx);
1309    let cx = &mut cx;
1310    let proxy = unsafe { Handle::from_raw(proxy) };
1311    let id = unsafe { Handle::from_raw(id) };
1312    let mut property_descriptor = unsafe { MutableHandle::from_raw(property_descriptor) };
1313    let is_none = unsafe { &mut *is_none };
1314
1315    // Step 1. Let W be the value of the [[Window]] internal slot of this.
1316    rooted!(&in(cx) let target = window_proxy_target(proxy));
1317    let window = WindowOrDissimilarOriginWindow::new(cx, target.handle());
1318
1319    // Step 2. If P is an array index property name:
1320    // Step 2.1. Let index be ! ToUint32(P).
1321    if let Some(index) = get_array_index_from_id(id) {
1322        // Step 2.2. Let children be the document-tree child navigables of W's associated Document.
1323        // Step 2.3. Let value be undefined.
1324        // Step 2.4. If index is less than children's size:
1325        if let Some(window_proxy) = window.window_proxy_for_child_navigable_at_index(index) {
1326            // Step 2.4.1. Sort children in ascending order, with navigableA being less than
1327            // navigableB if navigableA's container was inserted into W's
1328            // associated Document earlier than navigableB's container was.
1329            // Step 2.4.2. Set value to children[index]'s active WindowProxy.
1330            //
1331            // Note: These are handled by `window_proxy_for_child_navigable_at_index`.
1332            rooted!(&in(cx) let mut window_proxy_jsval = UndefinedValue());
1333            window_proxy.to_jsval(cx, window_proxy_jsval.handle_mut());
1334
1335            // 2.6. Return PropertyDescriptor { [[Value]]: value, [[Writable]]:
1336            // false, [[Enumerable]]: true, [[Configurable]]: true }.
1337            set_property_descriptor(
1338                property_descriptor,
1339                window_proxy_jsval.handle(),
1340                (JSPROP_ENUMERATE | JSPROP_READONLY) as u32,
1341                is_none,
1342            );
1343            return true;
1344        } else {
1345            // Step 2.5. If value is undefined:
1346            *is_none = true;
1347            // Step 2.5.1 If IsPlatformObjectSameOrigin(W) is true, then return
1348            // undefined.
1349            if is_platform_object_same_origin(cx, proxy) {
1350                return true;
1351            }
1352            // Step 2.5.2 Throw a "SecurityError" DOMException.
1353            return report_cross_origin_denial::<DomTypeHolder>(cx, id, "get");
1354        }
1355    }
1356
1357    // Step 3. If IsPlatformObjectSameOrigin(W) is true, then return ! OrdinaryGetOwnProperty(W, P).
1358    if is_platform_object_same_origin(cx, proxy) {
1359        return JS_GetOwnPropertyDescriptorById(
1360            cx,
1361            target.handle(),
1362            id,
1363            property_descriptor,
1364            is_none,
1365        );
1366    }
1367
1368    // Step 4. Let property be CrossOriginGetOwnPropertyHelper(W, P).
1369    if !cross_origin_get_own_property_helper(
1370        cx,
1371        proxy,
1372        window.cross_origin_properties(),
1373        id,
1374        property_descriptor.reborrow(),
1375        is_none,
1376    ) {
1377        return false;
1378    }
1379
1380    // Step 5. If property is not undefined, then return property.
1381    if !*is_none {
1382        return true;
1383    }
1384
1385    // Step 6. If property is undefined and P is in W's document-tree child navigable target name
1386    // property set:
1387    if let Some(named_child_navigable) = window.named_child_navigable(cx, id) {
1388        // Step 6.1. Let value be the active WindowProxy of the named object of W with the name P.
1389        rooted!(&in(cx) let mut window_proxy_value = UndefinedValue());
1390        named_child_navigable.to_jsval(cx, window_proxy_value.handle_mut());
1391        // Step 6.2 Return PropertyDescriptor { [[Value]]: value, [[Enumerable]]: false,
1392        // [[Writable]]: false, [[Configurable]]: true }.
1393        set_property_descriptor(
1394            property_descriptor.reborrow(),
1395            window_proxy_value.handle(),
1396            JSPROP_READONLY as u32,
1397            is_none,
1398        );
1399        return true;
1400    }
1401
1402    // Step 7. Return ? CrossOriginPropertyFallback(P).
1403    cross_origin_property_fallback::<DomTypeHolder>(
1404        cx,
1405        proxy,
1406        id,
1407        property_descriptor.reborrow(),
1408        is_none,
1409    )
1410}
1411
1412/// <https://html.spec.whatwg.org/multipage/#windowproxy-defineownproperty>
1413#[expect(unsafe_code)]
1414unsafe extern "C" fn define_property(
1415    cx: *mut RawJSContext,
1416    proxy: RawHandleObject,
1417    id: RawHandleId,
1418    desc: RawHandle<PropertyDescriptor>,
1419    res: *mut ObjectOpResult,
1420) -> bool {
1421    let mut cx = unsafe {
1422        // SAFETY: We are in a SpiderMonkey hook, so it is always safe to convert a raw context into
1423        // a mozjs context.
1424        JSContext::from_ptr(NonNull::new(cx).expect("JSContext should not be null in SM hook"))
1425    };
1426    let mut cx = CurrentRealm::assert(&mut cx);
1427    let cx = &mut cx;
1428    let id = unsafe { Handle::from_raw(id) };
1429    let proxy = unsafe { Handle::from_raw(proxy) };
1430
1431    // Step 1. Let W be the value of the [[Window]] internal slot of this.
1432    // Note: This is the `proxy` argument.
1433
1434    // Step 2. If IsPlatformObjectSameOrigin(W) is true:
1435    if is_platform_object_same_origin(cx, proxy) {
1436        // Step 2.1. If P is an array index property name, return false.
1437        if get_array_index_from_id(id).is_some() {
1438            // Spec says to Reject whether this is a supported index or not,
1439            // since we have no indexed setter or indexed creator.  That means
1440            // throwing in strict mode (FIXME: Bug 828137), doing nothing in
1441            // non-strict mode.
1442            unsafe {
1443                (*res).code_ = JSErrNum::JSMSG_CANT_DEFINE_WINDOW_ELEMENT as usize;
1444            }
1445            return true;
1446        }
1447
1448        // Step 2.2. Return ? OrdinaryDefineOwnProperty(W, P, Desc).
1449        rooted!(&in(cx) let target = window_proxy_target(proxy));
1450        return unsafe {
1451            JS_DefinePropertyById(cx.raw_cx(), target.handle().into(), id.into(), desc, res)
1452        };
1453    }
1454
1455    // Step 3. Throw a "SecurityError" DOMException.
1456    report_cross_origin_denial::<DomTypeHolder>(cx, id, "define")
1457}
1458
1459#[expect(unsafe_code)]
1460unsafe extern "C" fn has(
1461    cx: *mut RawJSContext,
1462    proxy: RawHandleObject,
1463    id: RawHandleId,
1464    bp: *mut bool,
1465) -> bool {
1466    unsafe { has_or_has_own(cx, proxy, id, bp, IncludePrototypes::Yes) }
1467}
1468
1469#[expect(unsafe_code)]
1470unsafe extern "C" fn has_own(
1471    cx: *mut RawJSContext,
1472    proxy: RawHandleObject,
1473    id: RawHandleId,
1474    bp: *mut bool,
1475) -> bool {
1476    unsafe { has_or_has_own(cx, proxy, id, bp, IncludePrototypes::No) }
1477}
1478
1479enum IncludePrototypes {
1480    Yes,
1481    No,
1482}
1483
1484#[expect(unsafe_code)]
1485unsafe fn has_or_has_own(
1486    cx: *mut RawJSContext,
1487    proxy: RawHandleObject,
1488    id: RawHandleId,
1489    bp: *mut bool,
1490    include_prototypes: IncludePrototypes,
1491) -> bool {
1492    let mut cx = unsafe { JSContext::from_ptr(ptr::NonNull::new(cx).unwrap()) };
1493    let mut cx = CurrentRealm::assert(&mut cx);
1494    let cx = &mut cx;
1495    let proxy = unsafe { Handle::from_raw(proxy) };
1496    let id = unsafe { Handle::from_raw(id) };
1497
1498    rooted!(&in(cx) let target = window_proxy_target(proxy));
1499    let window = WindowOrDissimilarOriginWindow::new(cx, target.handle());
1500
1501    let (success, found) = if is_platform_object_same_origin(cx, proxy) {
1502        if let Some(array_index) = get_array_index_from_id(id) &&
1503            window
1504                .window_proxy_for_child_navigable_at_index(array_index)
1505                .is_some()
1506        {
1507            unsafe { *bp = true };
1508            return true;
1509        }
1510
1511        let mut found = false;
1512        let success = match include_prototypes {
1513            IncludePrototypes::Yes => unsafe {
1514                JS_HasPropertyById(cx, target.handle(), id, &mut found)
1515            },
1516            IncludePrototypes::No => unsafe {
1517                JS_HasOwnPropertyById(cx, target.handle(), id, &mut found)
1518            },
1519        };
1520        (success, found)
1521    } else {
1522        rooted!(&in(cx) let mut property_descriptor = PropertyDescriptor::default());
1523        let mut is_none = false;
1524        let success = unsafe {
1525            get_own_property_descriptor(
1526                cx.raw_cx(),
1527                proxy.into(),
1528                id.into(),
1529                property_descriptor.handle_mut().into(),
1530                &mut is_none,
1531            )
1532        };
1533        (success, !is_none)
1534    };
1535
1536    if !success {
1537        return false;
1538    }
1539    unsafe { *bp = found };
1540    true
1541}
1542
1543/// <https://html.spec.whatwg.org/multipage/#windowproxy-get>
1544#[expect(unsafe_code)]
1545unsafe extern "C" fn get(
1546    cx: *mut RawJSContext,
1547    proxy: RawHandleObject,
1548    receiver: RawHandleValue,
1549    id: RawHandleId,
1550    return_value: RawMutableHandleValue,
1551) -> bool {
1552    let mut cx = unsafe {
1553        // SAFETY: We are in SM hook
1554        JSContext::from_ptr(NonNull::new(cx).expect("JSContext should not be null in SM hook"))
1555    };
1556    let mut cx = CurrentRealm::assert(&mut cx);
1557    let cx = &mut cx;
1558    let proxy = unsafe { Handle::from_raw(proxy) };
1559    let receiver = unsafe { Handle::from_raw(receiver) };
1560    let id = unsafe { Handle::from_raw(id) };
1561    let return_value = unsafe { MutableHandle::from_raw(return_value) };
1562
1563    // Step 1. Let W be the value of the [[Window]] internal slot of this.
1564    rooted!(&in(cx) let target = window_proxy_target(proxy));
1565    let window = WindowOrDissimilarOriginWindow::new(cx, target.handle());
1566
1567    // Step 2. Check if an access between two browsing contexts should be reported, given the
1568    // current global object's browsing context, W's browsing context, P, and the current settings
1569    // object.
1570    // TODO: Implement this.
1571
1572    // Step 3. If IsPlatformObjectSameOrigin(W) is true, then return ? OrdinaryGet(this, P, Receiver).
1573    if is_platform_object_same_origin(cx, proxy) {
1574        if let Some(index) = get_array_index_from_id(id) &&
1575            let Some(window_proxy) = window.window_proxy_for_child_navigable_at_index(index)
1576        {
1577            window_proxy.to_jsval(cx, return_value);
1578            return true;
1579        }
1580
1581        return unsafe { JS_ForwardGetPropertyTo(cx, target.handle(), id, receiver, return_value) };
1582    }
1583
1584    // Step 4. Return ? CrossOriginGet(this, P, Receiver).
1585    proxyhandler::cross_origin_get::<DomTypeHolder>(cx, proxy, receiver, id, return_value)
1586}
1587
1588/// <https://html.spec.whatwg.org/multipage/#windowproxy-set>
1589#[expect(unsafe_code)]
1590unsafe extern "C" fn set(
1591    cx: *mut RawJSContext,
1592    proxy: RawHandleObject,
1593    id: RawHandleId,
1594    v: RawHandleValue,
1595    receiver: RawHandleValue,
1596    res: *mut ObjectOpResult,
1597) -> bool {
1598    let mut cx = unsafe {
1599        // SAFETY: We are in SM hook
1600        JSContext::from_ptr(NonNull::new(cx).expect("JSContext should not be null in SM hook"))
1601    };
1602    let mut cx = CurrentRealm::assert(&mut cx);
1603    let cx = &mut cx;
1604
1605    // Step 1. Let W be the value of the [[Window]] internal slot of this.
1606    // Note: This is the `proxy` argument.
1607
1608    // Step 2. Check if an access between two browsing contexts should be reported, given the
1609    // current global object's browsing context, W's browsing context, P, and the current settings
1610    // object.
1611    // TODO: Implement this.
1612
1613    let proxy = unsafe { Handle::from_raw(proxy) };
1614    let id = unsafe { Handle::from_raw(id) };
1615
1616    // Step 3. If IsPlatformObjectSameOrigin(W) is true:
1617    if is_platform_object_same_origin(cx, proxy) {
1618        // Step 3.1. If P is an array index property name, then return false.
1619        if get_array_index_from_id(id).is_some() {
1620            // Reject (which means throw if and only if strict) the set.
1621            unsafe { (*res).code_ = JSErrNum::JSMSG_READ_ONLY as usize };
1622            return true;
1623        }
1624
1625        // Step 3.2. Return ? OrdinarySet(W, P, V, Receiver).
1626        rooted!(&in(cx) let target = window_proxy_target(proxy));
1627        return unsafe {
1628            JS_ForwardSetPropertyTo(
1629                cx.raw_cx(),
1630                target.handle().into(),
1631                id.into(),
1632                v,
1633                receiver,
1634                res,
1635            )
1636        };
1637    }
1638
1639    // Step 4. Return ? CrossOriginSet(this, P, V, Receiver).
1640    let receiver = unsafe { HandleValue::from_raw(receiver) };
1641    unsafe { cross_origin_set::<DomTypeHolder>(cx, proxy, id, v, receiver, res) }
1642}
1643
1644#[expect(unsafe_code)]
1645unsafe extern "C" fn get_prototype_if_ordinary(
1646    _: *mut RawJSContext,
1647    _: RawHandleObject,
1648    is_ordinary: *mut bool,
1649    _: RawMutableHandleObject,
1650) -> bool {
1651    // Window's [[GetPrototypeOf]] trap isn't the ordinary definition:
1652    //
1653    //   https://html.spec.whatwg.org/multipage/#windowproxy-getprototypeof
1654    //
1655    // We nonetheless can implement it with a static [[Prototype]], because
1656    // wrapper-class handlers (particularly, XOW in FilteringWrapper.cpp) supply
1657    // all non-ordinary behavior.
1658    //
1659    // But from a spec point of view, it's the exact same object in both cases --
1660    // only the observer's changed.  So this getPrototypeIfOrdinary trap on the
1661    // non-wrapper object *must* report non-ordinary, even if static [[Prototype]]
1662    // usually means ordinary.
1663    unsafe { *is_ordinary = false };
1664    true
1665}
1666
1667/// <https://html.spec.whatwg.org/multipage/#windowproxy-getprototypeof>
1668#[expect(unsafe_code)]
1669unsafe extern "C" fn get_prototype(
1670    cx: *mut RawJSContext,
1671    proxy: RawHandleObject,
1672    result: RawMutableHandleObject,
1673) -> bool {
1674    let mut cx = unsafe { JSContext::from_ptr(ptr::NonNull::new(cx).unwrap()) };
1675    let mut realm = CurrentRealm::assert(&mut cx);
1676    let proxy = unsafe { Handle::from_raw(proxy) };
1677    let result = unsafe { MutableHandleObject::from_raw(result) };
1678    maybe_cross_origin_get_prototype::<DomTypeHolder>(
1679        &mut realm,
1680        proxy,
1681        GetProtoObject::<DomTypeHolder>,
1682        result,
1683    )
1684}
1685
1686/// <https://html.spec.whatwg.org/multipage/#windowproxy-delete>
1687#[expect(unsafe_code)]
1688unsafe extern "C" fn delete(
1689    cx: *mut RawJSContext,
1690    proxy: RawHandleObject,
1691    id: RawHandleId,
1692    result: *mut ObjectOpResult,
1693) -> bool {
1694    let mut cx = unsafe { JSContext::from_ptr(ptr::NonNull::new(cx).unwrap()) };
1695    let mut cx = CurrentRealm::assert(&mut cx);
1696    let cx = &mut cx;
1697    let proxy = unsafe { Handle::from_raw(proxy) };
1698    let id = unsafe { Handle::from_raw(id) };
1699
1700    // Step 1. Let W be the value of the [[Window]] internal slot of this.
1701    rooted!(&in(cx) let target = window_proxy_target(proxy));
1702    let window = WindowOrDissimilarOriginWindow::new(cx, target.handle());
1703
1704    // Step 2. If IsPlatformObjectSameOrigin(W) is true:
1705    if is_platform_object_same_origin(cx, proxy) {
1706        // Step 2.1 If P is an array index property name:
1707        if let Some(array_index) = get_array_index_from_id(id) {
1708            // Step 2.1.1. Let desc be ! this.[[GetOwnProperty]](P).
1709            let code = if window
1710                .window_proxy_for_child_navigable_at_index(array_index)
1711                .is_none()
1712            {
1713                // Step 2.1.2. If desc is undefined, then return true.
1714                0 /* OkCode */
1715            } else {
1716                // Step 2.1.3. Return false.
1717                JSErrNum::JSMSG_CANT_DELETE_WINDOW_ELEMENT as usize
1718            };
1719            unsafe { (*result).code_ = code };
1720            return true;
1721        }
1722        // Step 2.2. Return ? OrdinaryDelete(W, P).
1723        rooted!(&in(cx) let target = window_proxy_target(proxy));
1724        return unsafe {
1725            JS_DeletePropertyById(cx.raw_cx(), target.handle().into(), id.into(), result)
1726        };
1727    }
1728
1729    // Step 3. Throw a "SecurityError" DOMException.
1730    report_cross_origin_denial::<DomTypeHolder>(cx, id, "delete")
1731}
1732
1733/// <https://html.spec.whatwg.org/multipage#windowproxy-ownpropertykeys>
1734#[expect(unsafe_code)]
1735unsafe extern "C" fn own_property_keys(
1736    cx: *mut RawJSContext,
1737    proxy: RawHandleObject,
1738    property_keys: RawMutableHandleIdVector,
1739) -> bool {
1740    let mut cx = unsafe { JSContext::from_ptr(ptr::NonNull::new(cx).unwrap()) };
1741    let mut cx = CurrentRealm::assert(&mut cx);
1742    let cx = &mut cx;
1743    let proxy = unsafe { Handle::from_raw(proxy) };
1744
1745    // Step 1. Let W be the value of the [[Window]] internal slot of this.
1746    rooted!(&in(cx) let target = window_proxy_target(proxy));
1747    let window = WindowOrDissimilarOriginWindow::new(cx, target.handle());
1748
1749    // Step 2. Let maxProperties be W's associated Document's document-tree child navigables's size.
1750    let max_properties = window.iframe_count();
1751
1752    // Step 3. Let keys be the range 0 to maxProperties, exclusive.
1753    rooted!(&in(cx) let mut rooted_index_jsid: jsid);
1754    for index in 0..max_properties {
1755        unsafe { int_to_jsid(index as i32, rooted_index_jsid.handle_mut()) };
1756        unsafe { AppendToIdVector(property_keys, rooted_index_jsid.handle()) };
1757    }
1758
1759    if is_platform_object_same_origin(cx, proxy) {
1760        // Step 4. If IsPlatformObjectSameOrigin(W) is true, then return the concatenation of keys and
1761        // OrdinaryOwnPropertyKeys(W).
1762        return GetPropertyKeys(
1763            cx,
1764            target.handle(),
1765            JSITER_OWNONLY | JSITER_HIDDEN | JSITER_SYMBOLS,
1766            property_keys,
1767        );
1768    }
1769
1770    // Step 5. Return the concatenation of keys and ! CrossOriginOwnPropertyKeys(W).
1771    cross_origin_own_property_keys(cx, proxy, window.cross_origin_properties(), property_keys)
1772}
1773
1774/// A version of <https://html.spec.whatwg.org/multipage#windowproxy-ownpropertykeys>
1775/// that hands back only the enumerable properties. This is necessary because the
1776/// default implementation of this method returns all enumerable properties which
1777/// isn't correct in the cross-origin case.
1778#[expect(unsafe_code)]
1779unsafe extern "C" fn get_own_enumerable_property_keys(
1780    cx: *mut RawJSContext,
1781    proxy: RawHandleObject,
1782    property_keys: RawMutableHandleIdVector,
1783) -> bool {
1784    let mut cx = unsafe { JSContext::from_ptr(ptr::NonNull::new(cx).unwrap()) };
1785    let mut cx = CurrentRealm::assert(&mut cx);
1786    let cx = &mut cx;
1787    let proxy = unsafe { Handle::from_raw(proxy) };
1788
1789    // Step 1. Let W be the value of the [[Window]] internal slot of this.
1790    rooted!(&in(cx) let target = window_proxy_target(proxy));
1791    let window = WindowOrDissimilarOriginWindow::new(cx, target.handle());
1792
1793    // Step 2. Let maxProperties be W's associated Document's document-tree child navigables's size.
1794    let max_properties = window.iframe_count();
1795
1796    // Step 3. Let keys be the range 0 to maxProperties, exclusive.
1797    rooted!(&in(cx) let mut rooted_index_jsid: jsid);
1798    for index in 0..max_properties {
1799        unsafe { int_to_jsid(index as i32, rooted_index_jsid.handle_mut()) };
1800        unsafe { AppendToIdVector(property_keys, rooted_index_jsid.handle()) };
1801    }
1802
1803    if is_platform_object_same_origin(cx, proxy) {
1804        // Step 4. If IsPlatformObjectSameOrigin(W) is true, then return the concatenation of keys and
1805        // OrdinaryOwnPropertyKeys(W).
1806        return GetPropertyKeys(cx, target.handle(), JSITER_OWNONLY, property_keys);
1807    }
1808
1809    // There are no other enumerable property keys for cross-origin WindowProxy other than
1810    // the child navigable indices.
1811    true
1812}
1813
1814#[expect(unsafe_code)]
1815unsafe extern "C" fn enumerate(
1816    cx: *mut RawJSContext,
1817    proxy: RawHandleObject,
1818    property_keys: RawMutableHandleIdVector,
1819) -> bool {
1820    // Just get the property keys from ourselves, in whatever Realm we happen to
1821    // be in. It's important to not enter the Realm of "proxy" here, because that
1822    // would affect the list of keys we claim to have.
1823    let mut cx = unsafe { JSContext::from_ptr(ptr::NonNull::new(cx).unwrap()) };
1824    let cx = &mut cx;
1825    let proxy = unsafe { Handle::from_raw(proxy) };
1826
1827    GetPropertyKeys(cx, proxy, 0, property_keys)
1828}
1829
1830static PROXY_TRAPS: ProxyTraps = ProxyTraps {
1831    enter: None,
1832    getOwnPropertyDescriptor: Some(get_own_property_descriptor),
1833    defineProperty: Some(define_property),
1834    ownPropertyKeys: Some(own_property_keys),
1835    delete_: Some(delete),
1836    enumerate: Some(enumerate),
1837    getPrototypeIfOrdinary: Some(get_prototype_if_ordinary),
1838    getPrototype: Some(get_prototype),
1839    setPrototype: Some(maybe_cross_origin_set_prototype_rawcx),
1840    setImmutablePrototype: None,
1841    preventExtensions: Some(prevent_extensions),
1842    isExtensible: Some(is_extensible),
1843    has: Some(has),
1844    get: Some(get),
1845    set: Some(set),
1846    call: None,
1847    construct: None,
1848    hasOwn: Some(has_own),
1849    getOwnEnumerablePropertyKeys: Some(get_own_enumerable_property_keys),
1850    nativeCall: None,
1851    objectClassIs: None,
1852    className: None,
1853    fun_toString: None,
1854    boxedValue_unbox: None,
1855    defaultValue: None,
1856    trace: Some(trace),
1857    finalize: Some(finalize),
1858    objectMoved: None,
1859    isCallable: None,
1860    isConstructor: None,
1861};
1862
1863/// Proxy handler for a WindowProxy.
1864/// Has ownership of the inner pointer and deallocates it when it is no longer needed.
1865pub(crate) struct WindowProxyHandler(*const libc::c_void);
1866
1867impl MallocSizeOf for WindowProxyHandler {
1868    fn size_of(&self, _ops: &mut MallocSizeOfOps) -> usize {
1869        // FIXME(#6907) this is a pointer to memory allocated by `new` in NewProxyHandler in rust-mozjs.
1870        0
1871    }
1872}
1873
1874// Safety: Send and Sync is guaranteed since the underlying pointer and all its associated methods in C++ are const.
1875#[expect(unsafe_code)]
1876unsafe impl Send for WindowProxyHandler {}
1877// Safety: Send and Sync is guaranteed since the underlying pointer and all its associated methods in C++ are const.
1878#[expect(unsafe_code)]
1879unsafe impl Sync for WindowProxyHandler {}
1880
1881#[expect(unsafe_code)]
1882impl WindowProxyHandler {
1883    fn new(traps: &ProxyTraps) -> Self {
1884        // Safety: Foreign function generated by bindgen. Pointer is freed in drop to prevent memory leak.
1885        let ptr = unsafe { CreateWrapperProxyHandler(traps) };
1886        assert!(!ptr.is_null());
1887        Self(ptr)
1888    }
1889
1890    /// Returns a single, shared WindowProxyHandler that contains normal PROXY_TRAPS.
1891    pub(crate) fn proxy_handler() -> &'static Self {
1892        use std::sync::OnceLock;
1893        /// We are sharing a single instance for the entire programs here due to lifetime issues.
1894        /// The pointer in self.0 is known to C++ and visited by the GC. Hence, we don't know when
1895        /// it is safe to free it.
1896        /// Sharing a single instance should be fine because all methods on this pointer in C++
1897        /// are const and don't modify its internal state.
1898        static SINGLETON: OnceLock<WindowProxyHandler> = OnceLock::new();
1899        SINGLETON.get_or_init(|| Self::new(&PROXY_TRAPS))
1900    }
1901
1902    /// Creates a new WindowProxy object on the C++ side and returns the pointer to it.
1903    /// The pointer should be owned by the GC.
1904    fn new_window_proxy(
1905        &self,
1906        cx: &mut JSContext,
1907        window_jsobject: js::gc::HandleObject,
1908    ) -> *mut JSObject {
1909        let obj = unsafe { NewWindowProxy(cx, window_jsobject, self.0) };
1910        assert!(!obj.is_null());
1911        obj
1912    }
1913}
1914
1915#[expect(unsafe_code)]
1916impl Drop for WindowProxyHandler {
1917    fn drop(&mut self) {
1918        // Safety: Pointer is allocated by corresponding C++ function, owned by this
1919        // struct and not accessible from outside.
1920        unsafe {
1921            DeleteWrapperProxyHandler(self.0);
1922        }
1923    }
1924}
1925
1926// How WindowProxy objects are garbage collected.
1927
1928#[expect(unsafe_code)]
1929unsafe extern "C" fn finalize(_fop: *mut GCContext, obj: *mut JSObject) {
1930    let mut slot = UndefinedValue();
1931    unsafe { GetProxyReservedSlot(obj, 0, &mut slot) };
1932    let this = slot.to_private() as *mut WindowProxy;
1933    if this.is_null() {
1934        // GC during obj creation or after transplanting.
1935        return;
1936    }
1937    unsafe {
1938        (*this).reflector.drop_memory(&*this);
1939        let jsobject = (*this).reflector.get_jsobject().get();
1940        debug!(
1941            "WindowProxy finalize: {:p}, with reflector {:p} from {:p}.",
1942            this, jsobject, obj
1943        );
1944        let _ = Box::from_raw(this);
1945    }
1946}
1947
1948#[expect(unsafe_code)]
1949unsafe extern "C" fn trace(trc: *mut JSTracer, obj: *mut JSObject) {
1950    let mut slot = UndefinedValue();
1951    unsafe { GetProxyReservedSlot(obj, 0, &mut slot) };
1952    let this = slot.to_private() as *const WindowProxy;
1953    if this.is_null() {
1954        // GC during obj creation or after transplanting.
1955        return;
1956    }
1957    unsafe { (*this).trace(trc) };
1958}
1959
1960/// A wrapper class for either a [`Window`] or [`DissimilarOriginWindow`] that
1961/// exposes a consistent interface for both of them.
1962enum WindowOrDissimilarOriginWindow {
1963    Window(DomRoot<Window>),
1964    DissimilarOriginWindow(DomRoot<DissimilarOriginWindow>),
1965}
1966
1967impl WindowOrDissimilarOriginWindow {
1968    fn new(cx: &mut JSContext, handle_object: HandleObject) -> Self {
1969        if let Ok(window) = root_from_handleobject::<Window>(cx, handle_object) {
1970            Self::Window(window)
1971        } else if let Ok(window) =
1972            root_from_handleobject::<DissimilarOriginWindow>(cx, handle_object)
1973        {
1974            Self::DissimilarOriginWindow(window)
1975        } else {
1976            unreachable!("WindowProxy should always be backed by some kind of window");
1977        }
1978    }
1979
1980    fn global_scope(&self) -> DomRoot<GlobalScope> {
1981        match self {
1982            WindowOrDissimilarOriginWindow::Window(window) => window.global(),
1983            WindowOrDissimilarOriginWindow::DissimilarOriginWindow(window) => window.global(),
1984        }
1985    }
1986
1987    fn window_proxy(&self) -> DomRoot<WindowProxy> {
1988        match self {
1989            WindowOrDissimilarOriginWindow::Window(window) => window.window_proxy(),
1990            WindowOrDissimilarOriginWindow::DissimilarOriginWindow(window) => window.window_proxy(),
1991        }
1992    }
1993
1994    #[expect(unsafe_code)]
1995    fn cross_origin_properties(&self) -> &'static CrossOriginProperties {
1996        match self {
1997            WindowOrDissimilarOriginWindow::Window(..) => unsafe {
1998                WindowBinding::CROSS_ORIGIN_PROPERTIES.get()
1999            },
2000            WindowOrDissimilarOriginWindow::DissimilarOriginWindow(..) => unsafe {
2001                DissimilarOriginWindowBinding::CROSS_ORIGIN_PROPERTIES.get()
2002            },
2003        }
2004    }
2005
2006    fn iframe_count(&self) -> u32 {
2007        match self {
2008            WindowOrDissimilarOriginWindow::Window(window) => window.Length(),
2009            WindowOrDissimilarOriginWindow::DissimilarOriginWindow(window) => window.Length(),
2010        }
2011    }
2012
2013    fn window_proxy_for_child_navigable_at_index(
2014        &self,
2015        index: u32,
2016    ) -> Option<DomRoot<WindowProxy>> {
2017        let window_proxy = self.window_proxy();
2018        let browsing_context_id = if let Some(document) = window_proxy.document() {
2019            document.iframes().at_insertion_index(index as usize)?
2020        } else {
2021            let parent_browsing_context_id = window_proxy.browsing_context_id();
2022            let (result_sender, result_receiver) = generic_channel::channel().unwrap();
2023            let _ = self.global_scope().script_to_constellation_chan().send(
2024                ScriptToConstellationMessage::GetChildBrowsingContextId(
2025                    parent_browsing_context_id,
2026                    index as usize,
2027                    result_sender,
2028                ),
2029            );
2030            result_receiver.recv().ok().flatten()?
2031        };
2032        ScriptThread::window_proxies().find_window_proxy(browsing_context_id)
2033    }
2034
2035    /// <https://html.spec.whatwg.org/multipage/#document-tree-child-navigable-target-name-property-set>
2036    ///
2037    /// > The document-tree child navigable target name property set of a Window object window is the
2038    /// > return value of running these steps:
2039    ///
2040    /// > Step 1. Let children be the document-tree child navigables of window's associated Document.
2041    /// > Step 2. Let firstNamedChildren be an empty ordered set.
2042    /// > Step 3. For each navigable of children:
2043    /// > Step 3.1. Let name be navigable's target name.
2044    /// > Step 3.2. If name is the empty string, then continue.
2045    /// > Step 3.3. If firstNamedChildren contains a navigable whose target name is name, then continue.
2046    /// > Step 3.4. Append navigable to firstNamedChildren.
2047    /// > Step 4. Let names be an empty ordered set.
2048    /// > Step 5. For each navigable of firstNamedChildren:
2049    /// > Step 5.1. Let name be navigable's target name.
2050    /// > Step 5.2. If navigable's active document's origin is same origin with window's relevant settings
2051    /// > object's origin, then append name to names.
2052    /// > Step 6. Return names.
2053    ///
2054    /// We don't implement these steps exactly, but we effectively do them using iterators below.
2055    fn named_child_navigable(
2056        &self,
2057        cx: &mut CurrentRealm,
2058        id: HandleId,
2059    ) -> Option<DomRoot<WindowProxy>> {
2060        // TODO: We cannot yet enumerate cross-origin child navigable target names.
2061        let Self::Window(window) = &self else {
2062            return None;
2063        };
2064
2065        let name = jsid_to_string(cx, id)?;
2066        if name.is_empty() {
2067            return None;
2068        }
2069        window
2070            .Document()
2071            .iframes()
2072            .iter()
2073            .filter_map(|iframe| iframe.GetContentWindow())
2074            .find(|window_proxy| window_proxy.get_name() == name)
2075    }
2076}