Skip to main content

script/dom/window/
location.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 dom_struct::dom_struct;
6use js::context::JSContext;
7use net_traits::request::Referrer;
8use script_bindings::dom::MutNullableDom;
9use script_bindings::reflector::{Reflector, reflect_dom_object};
10use servo_constellation_traits::{LoadData, LoadOrigin, NavigationHistoryBehavior};
11use servo_url::ServoUrl;
12
13use crate::dom::bindings::codegen::Bindings::LocationBinding::LocationMethods;
14use crate::dom::bindings::codegen::Bindings::WindowBinding::Window_Binding::WindowMethods;
15use crate::dom::bindings::error::{Error, ErrorResult, Fallible};
16use crate::dom::bindings::inheritance::Castable;
17use crate::dom::bindings::root::{Dom, DomRoot};
18use crate::dom::bindings::str::USVString;
19use crate::dom::dissimilaroriginwindow::DissimilarOriginWindow;
20use crate::dom::document::Document;
21use crate::dom::domstringlist::DOMStringList;
22use crate::dom::globalscope::GlobalScope;
23use crate::dom::urlhelper::UrlHelper;
24use crate::dom::window::Window;
25use crate::navigation::navigate;
26
27#[derive(PartialEq)]
28pub(crate) enum NavigationType {
29    /// The "[`Location`-object navigate][1]" steps.
30    ///
31    /// [1]: https://html.spec.whatwg.org/multipage/#location-object-navigate
32    Normal,
33
34    /// The last step of [`reload()`][1] (`reload_triggered == true`)
35    ///
36    /// [1]: https://html.spec.whatwg.org/multipage/#dom-location-reload
37    ReloadByScript,
38
39    /// User-requested navigation (the unlabeled paragraph after
40    /// [`reload()`][1]).
41    ///
42    /// [1]: https://html.spec.whatwg.org/multipage/#dom-location-reload
43    ReloadByConstellation,
44}
45
46#[derive(JSTraceable, MallocSizeOf)]
47#[cfg_attr(crown, crown::unrooted_must_root_lint::must_root)]
48enum LocationWindow {
49    SameOrigin(Dom<Window>),
50    DissimilarOrigin(Dom<DissimilarOriginWindow>),
51}
52
53impl LocationWindow {
54    fn same_origin_window(&self) -> Fallible<&Window> {
55        match self {
56            LocationWindow::SameOrigin(window) => Ok(window),
57            LocationWindow::DissimilarOrigin(..) => Err(Error::Security(Some(
58                "Tried to access same origin window on cross-origin object".into(),
59            ))),
60        }
61    }
62}
63
64#[dom_struct]
65pub(crate) struct Location {
66    reflector_: Reflector,
67    window: LocationWindow,
68    /// <https://html.spec.whatwg.org/multipage/#concept-location-empty-domstringlist>
69    empty_dom_string_list: MutNullableDom<DOMStringList>,
70}
71
72impl Location {
73    #[cfg_attr(crown, expect(crown::unrooted_must_root))]
74    fn new_inherited(window: LocationWindow) -> Self {
75        Location {
76            reflector_: Reflector::new(),
77            window,
78            empty_dom_string_list: Default::default(),
79        }
80    }
81
82    pub(crate) fn new(cx: &mut JSContext, window: &Window) -> DomRoot<Self> {
83        reflect_dom_object(
84            cx,
85            Box::new(Location::new_inherited(LocationWindow::SameOrigin(
86                Dom::from_ref(window),
87            ))),
88            window,
89        )
90    }
91
92    pub(crate) fn new_dissimilar_origin(
93        cx: &mut JSContext,
94        window: &DissimilarOriginWindow,
95    ) -> DomRoot<Self> {
96        reflect_dom_object(
97            cx,
98            Box::new(Location::new_inherited(LocationWindow::DissimilarOrigin(
99                Dom::from_ref(window),
100            ))),
101            window,
102        )
103    }
104
105    /// <https://html.spec.whatwg.org/multipage/#location-object-navigate>
106    fn navigate_a_location(
107        &self,
108        cx: &mut JSContext,
109        navigable: &Window,
110        url: ServoUrl,
111        history_handling: NavigationHistoryBehavior,
112    ) {
113        // Step 1. Let navigable be location's relevant global object's navigable.
114        let navigable_document = navigable.Document();
115        // Step 2. Let sourceDocument be the incumbent global object's associated Document.
116        let incumbent_global = GlobalScope::incumbent().expect("no incumbent global object");
117        let mut load_data = incumbent_global
118            .as_window()
119            .load_data_for_document(url, incumbent_global.pipeline_id());
120        load_data.about_base_url = navigable_document.about_base_url();
121        // Step 3. If location's relevant Document is not yet completely loaded,
122        // and the incumbent global object does not have transient activation, then set historyHandling to "replace".
123        //
124        // TODO: check for transient activation
125        let history_handling = if !navigable_document.completely_loaded() {
126            NavigationHistoryBehavior::Replace
127        } else {
128            history_handling
129        };
130        // Step 4. Navigate navigable to url using sourceDocument, with exceptionsEnabled set to true and historyHandling set to historyHandling.
131        navigate(cx, navigable, history_handling, false, load_data);
132    }
133
134    /// Navigate the relevant `Document`'s browsing context.
135    ///
136    /// This is ostensibly an implementation of
137    /// <https://html.spec.whatwg.org/multipage/#navigate>, but the specification has
138    /// greatly deviated from our code.
139    fn navigate(
140        &self,
141        cx: &mut JSContext,
142        window: &Window,
143        url: ServoUrl,
144        history_handling: NavigationHistoryBehavior,
145        navigation_type: NavigationType,
146    ) {
147        fn incumbent_window() -> DomRoot<Window> {
148            let incumbent_global = GlobalScope::incumbent().expect("no incumbent global object");
149            DomRoot::downcast(incumbent_global).expect("global object is not a Window")
150        }
151
152        // The active document of the source browsing context used for
153        // navigation determines the request's referrer and referrer policy.
154        let source_window = match navigation_type {
155            NavigationType::ReloadByScript | NavigationType::ReloadByConstellation => {
156                // > Navigate the browsing context [...] the source browsing context
157                // > set to the browsing context being navigated.
158                DomRoot::from_ref(window)
159            },
160            NavigationType::Normal => {
161                // > 2. Let `sourceBrowsingContext` be the incumbent global object's
162                // >    browsing context.
163                incumbent_window()
164            },
165        };
166        let source_document = source_window.Document();
167
168        let referrer = Referrer::ReferrerUrl(source_document.url());
169        let referrer_policy = source_document.get_referrer_policy();
170
171        // <https://html.spec.whatwg.org/multipage/#navigate>
172        // > Let `incumbentNavigationOrigin` be the origin of the incumbent
173        // > settings object, or if no script was involved, the origin of the
174        // > node document of the element that initiated the navigation.
175        let navigation_origin_window = match navigation_type {
176            NavigationType::Normal | NavigationType::ReloadByScript => incumbent_window(),
177            NavigationType::ReloadByConstellation => DomRoot::from_ref(window),
178        };
179        let (load_origin, creator_pipeline_id) = (
180            navigation_origin_window.origin().snapshot(),
181            Some(navigation_origin_window.pipeline_id()),
182        );
183
184        // Is `historyHandling` `reload`?
185        let reload_triggered = match navigation_type {
186            NavigationType::ReloadByScript | NavigationType::ReloadByConstellation => true,
187            NavigationType::Normal => false,
188        };
189
190        // Initiate navigation
191        // TODO: rethrow exceptions, set exceptions enabled flag.
192        let load_data = LoadData::new(
193            LoadOrigin::Script(load_origin),
194            url,
195            source_document.about_base_url(),
196            creator_pipeline_id,
197            referrer,
198            referrer_policy,
199            None, // Top navigation doesn't inherit secure context
200            Some(source_document.insecure_requests_policy()),
201            source_window
202                .as_global_scope()
203                .upgrade_insecure_navigations_set()
204                .clone(),
205            source_document.has_trustworthy_ancestor_origin(),
206            source_document.creation_sandboxing_flag_set_considering_parent_iframe(),
207        );
208        navigate(cx, window, history_handling, reload_triggered, load_data);
209    }
210
211    /// Get if this `Location`'s [relevant `Document`][1] is non-null.
212    ///
213    /// [1]: https://html.spec.whatwg.org/multipage/#relevant-document
214    fn has_document(&self) -> bool {
215        // <https://html.spec.whatwg.org/multipage/#relevant-document>
216        //
217        // > A `Location` object has an associated relevant `Document`, which is
218        // > this `Location` object's relevant global object's browsing
219        // > context's active document, if this `Location` object's relevant
220        // > global object's browsing context is non-null, and null otherwise.
221        self.window
222            .same_origin_window()
223            .is_ok_and(|window| window.Document().browsing_context().is_some())
224    }
225
226    /// Get this `Location` object's [relevant `Document`][1], or
227    /// `Err(Error::Security(..))` if it's non-null and its origin is not same
228    /// origin-domain with the entry setting object's origin.
229    ///
230    /// In the specification's terms:
231    ///
232    ///  1. If this `Location` object's relevant `Document` is null, then return
233    ///     null.
234    ///
235    ///  2. If this `Location` object's relevant `Document`'s origin is not same
236    ///     origin-domain with the entry settings object's origin, then throw a
237    ///     "`SecurityError`" `DOMException`.
238    ///
239    ///  3. Return this `Location` object's relevant `Document`.
240    ///
241    /// [1]: https://html.spec.whatwg.org/multipage/#relevant-document
242    fn document_if_same_origin(&self) -> Fallible<Option<DomRoot<Document>>> {
243        let window = self.window.same_origin_window()?;
244
245        // <https://html.spec.whatwg.org/multipage/#relevant-document>
246        //
247        // > A `Location` object has an associated relevant `Document`, which is
248        // > this `Location` object's relevant global object's browsing
249        // > context's active document, if this `Location` object's relevant
250        // > global object's browsing context is non-null, and null otherwise.
251        if let Some(window_proxy) = window.Document().browsing_context() {
252            // `Location`'s many other operations:
253            //
254            // > If this `Location` object's relevant `Document` is non-null and
255            // > its origin is not same origin-domain with the entry settings
256            // > object's origin, then throw a "SecurityError" `DOMException`.
257            //
258            // FIXME: We should still return the active document if it's same
259            //        origin but not fully active. `WindowProxy::document`
260            //        currently returns `None` in this case.
261            if let Some(document) = window_proxy.document().filter(|document| {
262                self.entry_settings_object()
263                    .origin()
264                    .same_origin_domain(&document.origin())
265            }) {
266                Ok(Some(document))
267            } else {
268                Err(Error::Security("Location's relevant Document is not same origin-domain with the entry settings object's origin".to_string().into()))
269            }
270        } else {
271            // The browsing context is null
272            Ok(None)
273        }
274    }
275
276    /// Get this `Location` object's [relevant url][1] or
277    /// `Err(Error::Security(..))` if the [relevant `Document`][2] if it's non-null
278    /// and its origin is not same origin-domain with the entry setting object's
279    /// origin.
280    ///
281    /// [1]: https://html.spec.whatwg.org/multipage/#concept-location-url
282    /// [2]: https://html.spec.whatwg.org/multipage/#relevant-document
283    fn get_url_if_same_origin(&self) -> Fallible<ServoUrl> {
284        Ok(if let Some(document) = self.document_if_same_origin()? {
285            document.url()
286        } else {
287            ServoUrl::parse("about:blank").unwrap()
288        })
289    }
290
291    fn entry_settings_object(&self) -> DomRoot<GlobalScope> {
292        GlobalScope::entry()
293    }
294
295    /// The common algorithm for `Location`'s setters and `Location::Assign`.
296    #[inline]
297    fn setter_common(
298        &self,
299        cx: &mut JSContext,
300        f: impl FnOnce(ServoUrl) -> Fallible<Option<ServoUrl>>,
301    ) -> ErrorResult {
302        // Step 1: If this Location object's relevant Document is null, then return.
303        // Step 2: If this Location object's relevant Document's origin is not
304        // same origin-domain with the entry settings object's origin, then
305        // throw a "SecurityError" DOMException.
306        if let Some(document) = self.document_if_same_origin()? {
307            // Step 3: Let copyURL be a copy of this Location object's url.
308            // Step 4: Assign the result of running f(copyURL) to copyURL.
309            if let Some(copy_url) = f(document.url())? {
310                // Step 5: Terminate these steps if copyURL is null.
311                // Step 6: Location-object navigate to copyURL.
312                self.navigate(
313                    cx,
314                    document.window(),
315                    copy_url,
316                    NavigationHistoryBehavior::Push,
317                    NavigationType::Normal,
318                );
319            }
320        }
321        Ok(())
322    }
323
324    /// Perform a user-requested reload (the unlabeled paragraph after
325    /// [`reload()`][1]).
326    ///
327    /// [1]: https://html.spec.whatwg.org/multipage/#dom-location-reload
328    pub(crate) fn reload_without_origin_check(&self, cx: &mut JSContext, window: &Window) {
329        // > When a user requests that the active document of a browsing context
330        // > be reloaded through a user interface element, the user agent should
331        // > navigate the browsing context to the same resource as that
332        // > `Document`, with `historyHandling` set to "reload".
333        let url = window.get_url();
334        self.navigate(
335            cx,
336            window,
337            url,
338            NavigationHistoryBehavior::Replace,
339            NavigationType::ReloadByConstellation,
340        );
341    }
342}
343
344impl LocationMethods<crate::DomTypeHolder> for Location {
345    /// <https://html.spec.whatwg.org/multipage/#dom-location-assign>
346    fn Assign(&self, cx: &mut JSContext, url: USVString) -> ErrorResult {
347        self.setter_common(cx, |_copy_url| {
348            // Step 3: Let urlRecord be the result of encoding-parsing a URL given url, relative to the entry settings object. If that failed,
349            // throw a "SyntaxError" DOMException.
350            let url = match self.entry_settings_object().encoding_parse_a_url(&url.0) {
351                Ok(url) => url,
352                Err(e) => return Err(Error::Syntax(Some(format!("Couldn't parse URL: {}", e)))),
353            };
354
355            Ok(Some(url))
356        })
357    }
358
359    /// <https://html.spec.whatwg.org/multipage/#dom-location-reload>
360    fn Reload(&self, cx: &mut JSContext) -> ErrorResult {
361        let window = self.window.same_origin_window()?;
362        let url = self.get_url_if_same_origin()?;
363        self.navigate(
364            cx,
365            window,
366            url,
367            NavigationHistoryBehavior::Replace,
368            NavigationType::ReloadByScript,
369        );
370        Ok(())
371    }
372
373    /// <https://html.spec.whatwg.org/multipage/#dom-location-replace>
374    fn Replace(&self, cx: &mut JSContext, url: USVString) -> ErrorResult {
375        // TODO: This should eventually support cross-origin operation.
376        let window = self.window.same_origin_window()?;
377
378        // Step 1: If this Location object's relevant Document is null, then return.
379        if self.has_document() {
380            // Step 2. Let urlRecord be the result of encoding-parsing a URL given url, relative to the entry settings object.
381            let url = match self.entry_settings_object().encoding_parse_a_url(&url.0) {
382                Ok(url) => url,
383                // Step 3. If urlRecord is failure, then throw a "SyntaxError" DOMException.
384                Err(e) => return Err(Error::Syntax(Some(format!("Couldn't parse URL: {}", e)))),
385            };
386            // Step 4. Location-object navigate this to urlRecord given "replace".
387            self.navigate_a_location(cx, window, url, NavigationHistoryBehavior::Replace);
388        }
389        Ok(())
390    }
391
392    /// <https://html.spec.whatwg.org/multipage/#dom-location-hash>
393    fn GetHash(&self) -> Fallible<USVString> {
394        Ok(UrlHelper::Hash(&self.get_url_if_same_origin()?))
395    }
396
397    /// <https://html.spec.whatwg.org/multipage/#dom-location-hash>
398    fn SetHash(&self, cx: &mut JSContext, value: USVString) -> ErrorResult {
399        let window = self.window.same_origin_window()?;
400
401        // Step 1. If this's relevant Document is null, then return.
402        if self.has_document() {
403            // Step 2. If this's relevant Document's origin is not same origin-domain
404            // with the entry settings object's origin, then throw a "SecurityError" DOMException.
405            // Step 3. Let copyURL be a copy of this's url.
406            let mut copy_url = self.get_url_if_same_origin()?;
407            // Step 4. Let thisURLFragment be copyURL's fragment if it is non-null; otherwise the empty string.
408            let this_url_fragment = copy_url.fragment().map(str::to_owned).unwrap_or_default();
409            // Step 6. Set copyURL's fragment to the empty string.
410            // Step 7. Basic URL parse input, with copyURL as url and fragment state as state override.
411            let input = &value.0;
412            // Note that if the hash is the empty string, we shouldn't then set the fragment to `None`.
413            // That's because the empty string is a valid hash target and should then scroll to the
414            // top of the document. Therefore, we don't use `UrlHelpers::SetHash` here, which would
415            // set it to `None`.
416            copy_url.set_fragment(match input {
417                // Step 5. Let input be the given value with a single leading "#" removed, if any.
418                _ if input.starts_with('#') => Some(&input[1..]),
419                _ => Some(input),
420            });
421            // Step 8. If copyURL's fragment is thisURLFragment, then return.
422            if copy_url.fragment() != Some(&this_url_fragment) {
423                // Step 9. Location-object navigate this to copyURL.
424                self.navigate_a_location(cx, window, copy_url, NavigationHistoryBehavior::Auto);
425            }
426        }
427        Ok(())
428    }
429
430    /// <https://html.spec.whatwg.org/multipage/#dom-location-host>
431    fn GetHost(&self) -> Fallible<USVString> {
432        Ok(UrlHelper::Host(&self.get_url_if_same_origin()?))
433    }
434
435    /// <https://html.spec.whatwg.org/multipage/#dom-location-host>
436    fn SetHost(&self, cx: &mut JSContext, value: USVString) -> ErrorResult {
437        self.setter_common(cx, |mut copy_url| {
438            // Step 4: If copyURL's cannot-be-a-base-URL flag is set, terminate these steps.
439            if copy_url.cannot_be_a_base() {
440                return Ok(None);
441            }
442
443            // Step 5: Basic URL parse the given value, with copyURL as url and host state
444            // as state override.
445            let _ = copy_url.as_mut_url().set_host(Some(&value.0));
446
447            Ok(Some(copy_url))
448        })
449    }
450
451    /// <https://html.spec.whatwg.org/multipage/#dom-location-origin>
452    fn GetOrigin(&self) -> Fallible<USVString> {
453        Ok(UrlHelper::Origin(&self.get_url_if_same_origin()?))
454    }
455
456    /// <https://html.spec.whatwg.org/multipage/#dom-location-hostname>
457    fn GetHostname(&self) -> Fallible<USVString> {
458        Ok(UrlHelper::Hostname(&self.get_url_if_same_origin()?))
459    }
460
461    /// <https://html.spec.whatwg.org/multipage/#dom-location-hostname>
462    fn SetHostname(&self, cx: &mut JSContext, value: USVString) -> ErrorResult {
463        self.setter_common(cx, |mut copy_url| {
464            // Step 4: If copyURL's cannot-be-a-base-URL flag is set, terminate these steps.
465            if copy_url.cannot_be_a_base() {
466                return Ok(None);
467            }
468
469            // Step 5: Basic URL parse the given value, with copyURL as url and hostname
470            // state as state override.
471            let _ = copy_url.as_mut_url().set_host(Some(&value.0));
472
473            Ok(Some(copy_url))
474        })
475    }
476
477    /// <https://html.spec.whatwg.org/multipage/#dom-location-href>
478    fn GetHref(&self) -> Fallible<USVString> {
479        Ok(UrlHelper::Href(&self.get_url_if_same_origin()?))
480    }
481
482    /// <https://html.spec.whatwg.org/multipage/#dom-location-href>
483    fn SetHref(&self, cx: &mut JSContext, value: USVString) -> ErrorResult {
484        let window = self.window.same_origin_window()?;
485
486        // Step 1. If this's relevant Document is null, then return.
487        if self.has_document() {
488            // Note: no call to self.check_same_origin_domain()
489            // Step 2: Let url be the result of encoding-parsing a URL given the given value, relative to the entry settings object.
490            let url = match self.entry_settings_object().encoding_parse_a_url(&value.0) {
491                Ok(url) => url,
492                // Step 3: If url is failure, then throw a "SyntaxError" DOMException.
493                Err(e) => return Err(Error::Syntax(Some(format!("Couldn't parse URL: {}", e)))),
494            };
495            // Step 4: Location-object navigate this to url.
496            self.navigate_a_location(cx, window, url, NavigationHistoryBehavior::Auto);
497        }
498        Ok(())
499    }
500
501    /// <https://html.spec.whatwg.org/multipage/#dom-location-pathname>
502    fn GetPathname(&self) -> Fallible<USVString> {
503        Ok(UrlHelper::Pathname(&self.get_url_if_same_origin()?))
504    }
505
506    /// <https://html.spec.whatwg.org/multipage/#dom-location-pathname>
507    fn SetPathname(&self, cx: &mut JSContext, value: USVString) -> ErrorResult {
508        self.setter_common(cx, |mut copy_url| {
509            // Step 4: If copyURL's cannot-be-a-base-URL flag is set, terminate these steps.
510            if copy_url.cannot_be_a_base() {
511                return Ok(None);
512            }
513
514            // Step 5: Set copyURL's path to the empty list.
515            // Step 6: Basic URL parse the given value, with copyURL as url and path
516            // start state as state override.
517            copy_url.as_mut_url().set_path(&value.0);
518
519            Ok(Some(copy_url))
520        })
521    }
522
523    /// <https://html.spec.whatwg.org/multipage/#dom-location-port>
524    fn GetPort(&self) -> Fallible<USVString> {
525        Ok(UrlHelper::Port(&self.get_url_if_same_origin()?))
526    }
527
528    /// <https://html.spec.whatwg.org/multipage/#dom-location-port>
529    fn SetPort(&self, cx: &mut JSContext, value: USVString) -> ErrorResult {
530        self.setter_common(cx, |mut copy_url| {
531            // Step 4: If copyURL cannot have a username/password/port, then return.
532            // https://url.spec.whatwg.org/#cannot-have-a-username-password-port
533            if copy_url.host().is_none() ||
534                copy_url.cannot_be_a_base() ||
535                copy_url.scheme() == "file"
536            {
537                return Ok(None);
538            }
539
540            // Step 5: If the given value is the empty string, then set copyURL's
541            // port to null.
542            // Step 6: Otherwise, basic URL parse the given value, with copyURL as url
543            // and port state as state override.
544            let _ = url::quirks::set_port(copy_url.as_mut_url(), &value.0);
545
546            Ok(Some(copy_url))
547        })
548    }
549
550    /// <https://html.spec.whatwg.org/multipage/#dom-location-protocol>
551    fn GetProtocol(&self) -> Fallible<USVString> {
552        Ok(UrlHelper::Protocol(&self.get_url_if_same_origin()?))
553    }
554
555    /// <https://html.spec.whatwg.org/multipage/#dom-location-protocol>
556    fn SetProtocol(&self, cx: &mut JSContext, value: USVString) -> ErrorResult {
557        self.setter_common(cx, |mut copy_url| {
558            // Step 4: Let possibleFailure be the result of basic URL parsing the given
559            // value, followed by ":", with copyURL as url and scheme start state as
560            // state override.
561            let scheme = match value.0.find(':') {
562                Some(position) => &value.0[..position],
563                None => &value.0,
564            };
565
566            if copy_url.as_mut_url().set_scheme(scheme).is_err() {
567                // Step 5: If possibleFailure is failure, then throw a "SyntaxError" DOMException.
568                return Err(Error::Syntax(
569                    "Couldn't parse URL scheme".to_string().into(),
570                ));
571            }
572
573            // Step 6: If copyURL's scheme is not an HTTP(S) scheme, then terminate these steps.
574            if !copy_url.scheme().eq_ignore_ascii_case("http") &&
575                !copy_url.scheme().eq_ignore_ascii_case("https")
576            {
577                return Ok(None);
578            }
579
580            Ok(Some(copy_url))
581        })
582    }
583
584    /// <https://html.spec.whatwg.org/multipage/#dom-location-search>
585    fn GetSearch(&self) -> Fallible<USVString> {
586        Ok(UrlHelper::Search(&self.get_url_if_same_origin()?))
587    }
588
589    /// <https://html.spec.whatwg.org/multipage/#dom-location-search>
590    fn SetSearch(&self, cx: &mut JSContext, value: USVString) -> ErrorResult {
591        self.setter_common(cx, |mut copy_url| {
592            // Step 4: If the given value is the empty string, set copyURL's query to null.
593            // Step 5: Otherwise, run these substeps:
594            //   1. Let input be the given value with a single leading "?" removed, if any.
595            //   2. Set copyURL's query to the empty string.
596            //   3. Basic URL parse input, with copyURL as url and query state as state
597            //      override, and the relevant Document's document's character encoding as
598            //      encoding override.
599            copy_url.as_mut_url().set_query(match value.0.as_str() {
600                "" => None,
601                _ if value.0.starts_with('?') => Some(&value.0[1..]),
602                _ => Some(&value.0),
603            });
604
605            Ok(Some(copy_url))
606        })
607    }
608
609    /// <https://html.spec.whatwg.org/multipage/#dom-location-ancestororigins>
610    fn GetAncestorOrigins(&self, cx: &mut JSContext) -> Fallible<DomRoot<DOMStringList>> {
611        let window = self.window.same_origin_window()?;
612
613        // Step 1. If this's relevant Document is null, then return this's empty DOMStringList.
614        if !self.has_document() {
615            return Ok(self
616                .empty_dom_string_list
617                .or_init(|| DOMStringList::new(cx, window.upcast(), vec![])));
618        }
619        // Step 2. If this's relevant Document's origin is not same origin-domain
620        // with the entry settings object's origin, then throw a "SecurityError" DOMException.
621        let document = window.Document();
622        if !document
623            .origin()
624            .same_origin_domain(&self.entry_settings_object().origin())
625        {
626            return Err(Error::Security("Location's relevant Document is not \
627                                                            same origin-domain with the entry settings object's \
628                                                            origin".to_string().into()));
629        }
630        // Step 3. Assert: this's relevant Document's ancestor origins list is not null.
631        // Step 4. Otherwise, return this's relevant Document's ancestor origins list.
632        Ok(document
633            .ancestor_origins_list()
634            .expect("Must always have ancestor origins initialized"))
635    }
636}