Skip to main content

script/dom/window/
history.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::cmp::Ordering;
7
8use dom_struct::dom_struct;
9use js::context::JSContext;
10use js::jsapi::Heap;
11use js::jsval::{JSVal, NullValue, UndefinedValue};
12use js::rust::{HandleValue, MutableHandleValue};
13use net_traits::CoreResourceMsg;
14use profile_traits::generic_channel;
15use script_bindings::reflector::{Reflector, reflect_dom_object};
16use servo_base::generic_channel::GenericSend;
17use servo_base::id::HistoryStateId;
18use servo_constellation_traits::{
19    HistoryTraversalSource, ScriptToConstellationMessage, SessionHistoryTraversalRequest,
20    StructuredSerializedData, TraversalDirection,
21};
22use servo_url::ServoUrl;
23
24use crate::dom::bindings::codegen::Bindings::HistoryBinding::HistoryMethods;
25use crate::dom::bindings::codegen::Bindings::LocationBinding::Location_Binding::LocationMethods;
26use crate::dom::bindings::codegen::Bindings::WindowBinding::WindowMethods;
27use crate::dom::bindings::error::{Error, ErrorResult, Fallible};
28use crate::dom::bindings::inheritance::Castable;
29use crate::dom::bindings::reflector::DomGlobal;
30use crate::dom::bindings::root::{AsHandleValue, Dom, DomRoot};
31use crate::dom::bindings::str::{DOMString, USVString};
32use crate::dom::bindings::structuredclone;
33use crate::dom::event::Event;
34use crate::dom::eventtarget::EventTarget;
35use crate::dom::hashchangeevent::HashChangeEvent;
36use crate::dom::popstateevent::PopStateEvent;
37use crate::dom::window::Window;
38
39enum PushOrReplace {
40    Push,
41    Replace,
42}
43
44/// <https://html.spec.whatwg.org/multipage/#the-history-interface>
45#[dom_struct]
46pub(crate) struct History {
47    reflector_: Reflector,
48    window: Dom<Window>,
49    #[ignore_malloc_size_of = "mozjs"]
50    state: Heap<JSVal>,
51    #[no_trace]
52    state_id: Cell<Option<HistoryStateId>>,
53}
54
55impl History {
56    pub(crate) fn new_inherited(window: &Window) -> History {
57        History {
58            reflector_: Reflector::new(),
59            window: Dom::from_ref(window),
60            state: Heap::default(),
61            state_id: Cell::new(None),
62        }
63    }
64
65    pub(crate) fn new(cx: &mut JSContext, window: &Window) -> DomRoot<History> {
66        let dom_root = reflect_dom_object(cx, Box::new(History::new_inherited(window)), window);
67        dom_root.state.set(NullValue());
68        dom_root
69    }
70}
71
72impl History {
73    fn traverse_history(&self, direction: TraversalDirection) -> ErrorResult {
74        if !self.window.Document().is_fully_active() {
75            return Err(Error::Security(None));
76        }
77        let _ = self
78            .window
79            .as_global_scope()
80            .script_to_constellation_chan()
81            .send(ScriptToConstellationMessage::TraverseHistory(
82                SessionHistoryTraversalRequest::new(
83                    self.window.webview_id(),
84                    direction,
85                    HistoryTraversalSource::Script,
86                ),
87            ));
88        Ok(())
89    }
90
91    /// <https://html.spec.whatwg.org/multipage/#history-traversal>
92    /// Steps 5-16
93    pub(crate) fn activate_state(
94        &self,
95        cx: &mut JSContext,
96        state_id: Option<HistoryStateId>,
97        url: ServoUrl,
98    ) {
99        // Steps 5
100        let document = self.window.Document();
101        let old_url = document.url();
102        document.set_url(url.clone());
103
104        // Step 6
105        let hash_changed = old_url.fragment() != url.fragment();
106
107        // Step 8
108        if let Some(fragment) = url.fragment() {
109            document.scroll_to_the_fragment(cx, fragment);
110        }
111
112        // Step 11
113        let state_changed = state_id != self.state_id.get();
114        self.state_id.set(state_id);
115        let serialized_data = match state_id {
116            Some(state_id) => {
117                let (tx, rx) =
118                    generic_channel::channel(self.global().time_profiler_chan().clone()).unwrap();
119                let _ = self
120                    .window
121                    .as_global_scope()
122                    .resource_threads()
123                    .send(CoreResourceMsg::GetHistoryState(state_id, tx));
124                rx.recv().unwrap()
125            },
126            None => None,
127        };
128
129        match serialized_data {
130            Some(data) => {
131                let data = StructuredSerializedData {
132                    serialized: data,
133                    ..Default::default()
134                };
135                rooted!(&in(cx) let mut state = UndefinedValue());
136                if structuredclone::read(
137                    cx,
138                    self.window.as_global_scope(),
139                    data,
140                    state.handle_mut(),
141                )
142                .is_err()
143                {
144                    warn!("Error reading structuredclone data");
145                }
146                self.state.set(state.get());
147            },
148            None => {
149                self.state.set(NullValue());
150            },
151        }
152
153        // TODO: Queue events on DOM Manipulation task source if non-blocking flag is set.
154        // Step 16.1
155        if state_changed {
156            PopStateEvent::dispatch_jsval(
157                cx,
158                self.window.upcast::<EventTarget>(),
159                &self.window,
160                self.state.as_handle_value(),
161            );
162        }
163
164        // Step 16.3
165        if hash_changed {
166            let event = HashChangeEvent::new(
167                cx,
168                &self.window,
169                atom!("hashchange"),
170                false,
171                false,
172                old_url.into_string(),
173                url.into_string(),
174            );
175            event
176                .upcast::<Event>()
177                .fire(cx, self.window.upcast::<EventTarget>());
178        }
179    }
180
181    pub(crate) fn remove_states(&self, states: Vec<HistoryStateId>) {
182        let _ = self
183            .window
184            .as_global_scope()
185            .resource_threads()
186            .send(CoreResourceMsg::RemoveHistoryStates(states));
187    }
188
189    /// <https://html.spec.whatwg.org/multipage/#dom-history-pushstate>
190    /// <https://html.spec.whatwg.org/multipage/#dom-history-replacestate>
191    fn push_or_replace_state(
192        &self,
193        cx: &mut JSContext,
194        data: HandleValue,
195        _title: DOMString,
196        url: Option<USVString>,
197        push_or_replace: PushOrReplace,
198    ) -> ErrorResult {
199        // Step 1
200        let document = self.window.Document();
201
202        // Step 2
203        if !document.is_fully_active() {
204            return Err(Error::Security(None));
205        }
206
207        // TODO: Step 3 Optionally abort these steps
208        // https://github.com/servo/servo/issues/19159
209
210        // Step 4. Let serializedData be StructuredSerializeForStorage(data). Rethrow any exceptions.
211        let serialized_data = structuredclone::write(cx, data, None)?;
212
213        // Step 5. Let newURL be document's URL.
214        let new_url: ServoUrl = match url {
215            // Step 6. If url is not null or the empty string, then:
216            Some(urlstring) => {
217                let document_url = document.url();
218
219                // Step 6.1 Set newURL to the result of encoding-parsing a URL given url,
220                // relative to the relevant settings object of history.
221                let Ok(url) = ServoUrl::parse_with_base(Some(&document_url), &urlstring.0) else {
222                    // Step 6.2 If newURL is failure, then throw a "SecurityError" DOMException.
223                    return Err(Error::Security(None));
224                };
225
226                // Step 6.3 If document cannot have its URL rewritten to newURL,
227                // then throw a "SecurityError" DOMException.
228                if !Self::can_have_url_rewritten(&document_url, &url) {
229                    return Err(Error::Security(None));
230                }
231
232                url
233            },
234            None => document.url(),
235        };
236
237        // Step 8
238        let state_id = match push_or_replace {
239            PushOrReplace::Push => {
240                let state_id = HistoryStateId::new();
241                self.state_id.set(Some(state_id));
242                let msg = ScriptToConstellationMessage::PushHistoryState(state_id, new_url.clone());
243                let _ = self
244                    .window
245                    .as_global_scope()
246                    .script_to_constellation_chan()
247                    .send(msg);
248                state_id
249            },
250            PushOrReplace::Replace => {
251                let state_id = match self.state_id.get() {
252                    Some(state_id) => state_id,
253                    None => {
254                        let state_id = HistoryStateId::new();
255                        self.state_id.set(Some(state_id));
256                        state_id
257                    },
258                };
259                let msg =
260                    ScriptToConstellationMessage::ReplaceHistoryState(state_id, new_url.clone());
261                let _ = self
262                    .window
263                    .as_global_scope()
264                    .script_to_constellation_chan()
265                    .send(msg);
266                state_id
267            },
268        };
269
270        let _ = self.window.as_global_scope().resource_threads().send(
271            CoreResourceMsg::SetHistoryState(state_id, serialized_data.serialized.clone()),
272        );
273
274        // TODO: Step 9 Update current entry to represent a GET request
275        // https://github.com/servo/servo/issues/19156
276
277        // Step 10
278        document.set_url(new_url);
279
280        // Step 11
281        rooted!(&in(cx) let mut state = UndefinedValue());
282        if structuredclone::read(
283            cx,
284            self.window.as_global_scope(),
285            serialized_data,
286            state.handle_mut(),
287        )
288        .is_err()
289        {
290            warn!("Error reading structuredclone data");
291        }
292
293        // Step 12
294        self.state.set(state.get());
295
296        // TODO: Step 13 Update Document's latest entry to current entry
297        // https://github.com/servo/servo/issues/19158
298
299        Ok(())
300    }
301
302    /// <https://html.spec.whatwg.org/multipage/#can-have-its-url-rewritten>
303    /// Step 2-6
304    fn can_have_url_rewritten(document_url: &ServoUrl, target_url: &ServoUrl) -> bool {
305        // Step 2. If targetURL and documentURL differ in their scheme, username,
306        // password, host, or port components, then return false.
307        if target_url.scheme() != document_url.scheme() ||
308            target_url.username() != document_url.username() ||
309            target_url.password() != document_url.password() ||
310            target_url.host() != document_url.host() ||
311            target_url.port() != document_url.port()
312        {
313            return false;
314        }
315
316        // Step 3. If targetURL's scheme is an HTTP(S) scheme, then return true.
317        if target_url.scheme() == "http" || target_url.scheme() == "https" {
318            return true;
319        }
320
321        // Step 4. If targetURL's scheme is "file", then:
322        if target_url.scheme() == "file" {
323            // Step 4.1 If targetURL and documentURL differ in their path component, then return false.
324            // Step 4.2 Return true.
325            return target_url.path() == document_url.path();
326        }
327
328        // Step 5. If targetURL and documentURL differ in their path component
329        // or query components, then return false.
330        if target_url.path() != document_url.path() || target_url.query() != document_url.query() {
331            return false;
332        }
333
334        // Step 6. Return true.
335        true
336    }
337}
338
339impl HistoryMethods<crate::DomTypeHolder> for History {
340    /// <https://html.spec.whatwg.org/multipage/#dom-history-state>
341    fn GetState(&self, _cx: &mut JSContext, mut retval: MutableHandleValue) -> Fallible<()> {
342        if !self.window.Document().is_fully_active() {
343            return Err(Error::Security(None));
344        }
345        retval.set(self.state.get());
346        Ok(())
347    }
348
349    /// <https://html.spec.whatwg.org/multipage/#dom-history-length>
350    fn GetLength(&self) -> Fallible<u32> {
351        if !self.window.Document().is_fully_active() {
352            return Err(Error::Security(None));
353        }
354
355        let Some((sender, recv)) =
356            generic_channel::channel(self.global().time_profiler_chan().clone())
357        else {
358            return Err(Error::InvalidState(None));
359        };
360
361        let msg = ScriptToConstellationMessage::JointSessionHistoryLength(sender);
362
363        self.window
364            .as_global_scope()
365            .script_to_constellation_chan()
366            .send(msg)
367            .map_err(|_| Error::InvalidState(None))?;
368
369        recv.recv().map_err(|_| Error::InvalidState(None))
370    }
371
372    /// <https://html.spec.whatwg.org/multipage/#dom-history-go>
373    fn Go(&self, cx: &mut JSContext, delta: i32) -> ErrorResult {
374        let direction = match delta.cmp(&0) {
375            Ordering::Greater => TraversalDirection::Forward(delta as usize),
376            Ordering::Less => TraversalDirection::Back(-delta as usize),
377            Ordering::Equal => return self.window.Location(cx).Reload(cx),
378        };
379
380        self.traverse_history(direction)
381    }
382
383    /// <https://html.spec.whatwg.org/multipage/#dom-history-back>
384    fn Back(&self) -> ErrorResult {
385        self.traverse_history(TraversalDirection::Back(1))
386    }
387
388    /// <https://html.spec.whatwg.org/multipage/#dom-history-forward>
389    fn Forward(&self) -> ErrorResult {
390        self.traverse_history(TraversalDirection::Forward(1))
391    }
392
393    /// <https://html.spec.whatwg.org/multipage/#dom-history-pushstate>
394    fn PushState(
395        &self,
396        cx: &mut JSContext,
397        data: HandleValue,
398        title: DOMString,
399        url: Option<USVString>,
400    ) -> ErrorResult {
401        self.push_or_replace_state(cx, data, title, url, PushOrReplace::Push)
402    }
403
404    /// <https://html.spec.whatwg.org/multipage/#dom-history-replacestate>
405    fn ReplaceState(
406        &self,
407        cx: &mut JSContext,
408        data: HandleValue,
409        title: DOMString,
410        url: Option<USVString>,
411    ) -> ErrorResult {
412        self.push_or_replace_state(cx, data, title, url, PushOrReplace::Replace)
413    }
414}