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