Skip to main content

script/dom/html/embedded_content/
htmliframeelement.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::rc::Rc;
7
8use content_security_policy::sandboxing_directive::{
9    SandboxingFlagSet, parse_a_sandboxing_directive,
10};
11use dom_struct::dom_struct;
12use embedder_traits::ViewportDetails;
13use html5ever::{LocalName, Prefix, local_name, ns};
14use js::context::JSContext;
15use js::rust::HandleObject;
16use net_traits::ReferrerPolicy;
17use net_traits::request::Destination;
18use profile_traits::generic_channel::channel;
19use script_bindings::cell::DomRefCell;
20use script_traits::{NewPipelineInfo, UpdatePipelineIdReason};
21use servo_base::id::{BrowsingContextId, PipelineId, WebViewId};
22use servo_constellation_traits::{
23    IFrameLoadInfo, IFrameLoadInfoWithData, LoadData, LoadOrigin, NavigationHistoryBehavior,
24    ScriptToConstellationMessage, TargetSnapshotParams,
25};
26use servo_url::ServoUrl;
27use style::attr::{AttrValue, LengthOrPercentageOrAuto};
28use stylo_atoms::Atom;
29
30use crate::dom::bindings::codegen::Bindings::HTMLIFrameElementBinding::HTMLIFrameElementMethods;
31use crate::dom::bindings::codegen::Bindings::WindowBinding::Window_Binding::WindowMethods;
32use crate::dom::bindings::codegen::UnionTypes::TrustedHTMLOrString;
33use crate::dom::bindings::error::Fallible;
34use crate::dom::bindings::inheritance::Castable;
35use crate::dom::bindings::refcounted::Trusted;
36use crate::dom::bindings::reflector::DomGlobal;
37use crate::dom::bindings::root::{DomRoot, LayoutDom, MutNullableDom};
38use crate::dom::bindings::str::{DOMString, USVString};
39use crate::dom::document::Document;
40use crate::dom::domtokenlist::DOMTokenList;
41use crate::dom::element::attributes::storage::AttrRef;
42use crate::dom::element::{AttributeMutation, Element, reflect_referrer_policy_attribute};
43use crate::dom::eventtarget::EventTarget;
44use crate::dom::html::htmlelement::HTMLElement;
45use crate::dom::node::virtualmethods::VirtualMethods;
46use crate::dom::node::{BindContext, Node, NodeDamage, NodeTraits, UnbindContext};
47use crate::dom::performance::performanceresourcetiming::InitiatorType;
48use crate::dom::trustedtypes::trustedhtml::TrustedHTML;
49use crate::dom::windowproxy::WindowProxy;
50use crate::event_loop::document_loader::{LoadBlocker, LoadType};
51use crate::event_loop::script_thread::{ScriptThread, with_script_thread};
52use crate::event_loop::script_window_proxies::ScriptWindowProxies;
53use crate::fetch::network_listener::ResourceTimingListener;
54use crate::navigation::{
55    determine_creation_sandboxing_flags, determine_iframe_element_referrer_policy,
56};
57
58#[derive(PartialEq)]
59enum PipelineType {
60    InitialAboutBlank,
61    Navigation,
62}
63
64#[derive(Clone, Copy, PartialEq)]
65pub(crate) enum ProcessingMode {
66    FirstTime,
67    NotFirstTime,
68}
69
70/// <https://html.spec.whatwg.org/multipage/#lazy-load-resumption-steps>
71#[derive(Clone, Copy, Default, MallocSizeOf, PartialEq)]
72enum LazyLoadResumptionSteps {
73    #[default]
74    None,
75    SrcDoc,
76}
77
78#[dom_struct]
79pub(crate) struct HTMLIFrameElement {
80    htmlelement: HTMLElement,
81    #[no_trace]
82    webview_id: Cell<Option<WebViewId>>,
83    #[no_trace]
84    browsing_context_id: Cell<Option<BrowsingContextId>>,
85    #[no_trace]
86    pipeline_id: Cell<Option<PipelineId>>,
87    #[no_trace]
88    pending_pipeline_id: Cell<Option<PipelineId>>,
89    #[no_trace]
90    about_blank_pipeline_id: Cell<Option<PipelineId>>,
91    sandbox: MutNullableDom<DOMTokenList>,
92    #[no_trace]
93    sandboxing_flag_set: Cell<Option<SandboxingFlagSet>>,
94    load_blocker: DomRefCell<Option<LoadBlocker>>,
95    #[conditional_malloc_size_of]
96    script_window_proxies: Rc<ScriptWindowProxies>,
97    /// <https://html.spec.whatwg.org/multipage/#current-navigation-was-lazy-loaded>
98    current_navigation_was_lazy_loaded: Cell<bool>,
99    /// <https://html.spec.whatwg.org/multipage/#lazy-load-resumption-steps>
100    #[no_trace]
101    lazy_load_resumption_steps: Cell<LazyLoadResumptionSteps>,
102    /// Keeping track of whether the iframe will be navigated
103    /// outside of the processing of it's attribute(for example: form navigation).
104    /// This is necessary to prevent the iframe load event steps
105    /// from asynchronously running for the initial blank document
106    /// while script at this point(when the flag is set)
107    /// expects those to run only for the navigated documented.
108    pending_navigation: Cell<bool>,
109    /// Initial name set by the content of the `name` attribute on the
110    /// iframe. This is frozen in time, since it is only processed once
111    /// on the initial creation of the iframe contents. If the iframe
112    /// itself changes the `window.name`, that takes precedence.
113    frozen_name: DomRefCell<Option<String>>,
114}
115
116impl HTMLIFrameElement {
117    /// <https://html.spec.whatwg.org/multipage/#lazy-load-resumption-steps>
118    pub(crate) fn has_lazy_load_resumption_steps(&self) -> bool {
119        !matches!(
120            self.lazy_load_resumption_steps.get(),
121            LazyLoadResumptionSteps::None
122        )
123    }
124
125    /// Run and clear this iframe's lazy load resumption steps, if it has any.
126    /// <https://html.spec.whatwg.org/multipage/#lazy-load-resumption-steps>
127    pub(crate) fn resume_lazy_load(&self, cx: &mut JSContext) {
128        let previous_resumption_steps = self
129            .lazy_load_resumption_steps
130            .replace(LazyLoadResumptionSteps::None);
131        match previous_resumption_steps {
132            LazyLoadResumptionSteps::None => (),
133            LazyLoadResumptionSteps::SrcDoc => {
134                self.navigate_to_the_srcdoc_resource(cx, ProcessingMode::NotFirstTime);
135            },
136        }
137    }
138
139    /// <https://html.spec.whatwg.org/multipage/#shared-attribute-processing-steps-for-iframe-and-frame-elements>,
140    fn shared_attribute_processing_steps_for_iframe_and_frame_elements(
141        &self,
142        _mode: ProcessingMode,
143    ) -> Option<ServoUrl> {
144        let element = self.upcast::<Element>();
145        // Step 2. If element has a src attribute specified, and its value is not the empty string, then:
146        let url = element
147            .get_attribute_string_value(&local_name!("src"))
148            .and_then(|url| {
149                if url.is_empty() {
150                    None
151                } else {
152                    // Step 2.1. Let maybeURL be the result of encoding-parsing a URL given that attribute's value,
153                    // relative to element's node document.
154                    // Step 2.2. If maybeURL is not failure, then set url to maybeURL.
155                    self.owner_document().encoding_parse_a_url(&url).ok()
156                }
157            })
158            // Step 1. Let url be the URL record about:blank.
159            .unwrap_or_else(|| ServoUrl::parse("about:blank").unwrap());
160        // Step 3. If the inclusive ancestor navigables of element's node navigable contains
161        // a navigable whose active document's URL equals url with exclude fragments set to true, then return null.
162        // TODO
163
164        // Step 4. If url matches about:blank and initialInsertion is true, then perform the URL and history update steps
165        // given element's content navigable's active document and url.
166        // TODO
167
168        // Step 5. Return url.
169        Some(url)
170    }
171
172    pub(crate) fn navigate_or_reload_child_browsing_context(
173        &self,
174        cx: &mut JSContext,
175        load_data: LoadData,
176        history_handling: NavigationHistoryBehavior,
177        mode: ProcessingMode,
178        target_snapshot_params: TargetSnapshotParams,
179    ) {
180        // <https://html.spec.whatwg.org/multipage/#navigate>
181        // Step 11. If container is an iframe element and will lazy load element steps
182        // given container returns true, then stop intersection-observing a lazy loading
183        // element container and set container's lazy load resumption steps to null.
184        if self.will_lazy_load_element_steps() {
185            self.owner_document()
186                .stop_intersection_observing_a_lazy_loading_element(
187                    cx.no_gc(),
188                    self.upcast::<Element>(),
189                );
190            self.lazy_load_resumption_steps
191                .set(LazyLoadResumptionSteps::None);
192        }
193
194        self.start_new_pipeline(
195            cx,
196            load_data,
197            PipelineType::Navigation,
198            history_handling,
199            mode,
200            target_snapshot_params,
201        );
202    }
203
204    fn start_new_pipeline(
205        &self,
206        cx: &mut JSContext,
207        mut load_data: LoadData,
208        pipeline_type: PipelineType,
209        history_handling: NavigationHistoryBehavior,
210        mode: ProcessingMode,
211        target_snapshot_params: TargetSnapshotParams,
212    ) {
213        let document = self.owner_document();
214
215        {
216            let load_blocker = &self.load_blocker;
217            // Any oustanding load is finished from the point of view of the blocked
218            // document; the new navigation will continue blocking it.
219            LoadBlocker::terminate(cx, load_blocker);
220
221            *load_blocker.borrow_mut() = Some(LoadBlocker::new(
222                &document,
223                LoadType::Subframe(load_data.url.clone()),
224            ));
225        }
226
227        if load_data.url.scheme() != "javascript" {
228            self.continue_navigation(
229                cx,
230                load_data,
231                pipeline_type,
232                history_handling,
233                target_snapshot_params,
234            );
235            return;
236        }
237
238        // TODO(jdm): The spec uses the navigate algorithm here, but
239        //   our iframe navigation is not yet unified enough to follow that.
240        //   Eventually we should remove the task and invoke ScriptThread::navigate instead.
241        let iframe = Trusted::new(self);
242        let doc = Trusted::new(&*document);
243        document
244            .global()
245            .task_manager()
246            .networking_task_source()
247            .queue(task!(navigate_to_javascript: move |cx| {
248                let this = iframe.root();
249                let window_proxy = this.GetContentWindow();
250                if let Some(window_proxy) = window_proxy {
251                    // If this method returns false we are not creating a new
252                    // document and the frame can be considered loaded.
253                    if !ScriptThread::navigate_to_javascript_url(
254                        cx,
255                        &this.owner_global(),
256                        &window_proxy.global(),
257                        &mut load_data,
258                        Some(this.upcast()),
259                        Some(mode == ProcessingMode::FirstTime),
260                    ) {
261                        LoadBlocker::terminate(cx, &this.load_blocker);
262                        return;
263                    }
264                    load_data.about_base_url = doc.root().about_base_url();
265                }
266                this.continue_navigation(cx, load_data, pipeline_type, history_handling, target_snapshot_params);
267            }));
268    }
269
270    fn continue_navigation(
271        &self,
272        cx: &mut JSContext,
273        load_data: LoadData,
274        pipeline_type: PipelineType,
275        history_handling: NavigationHistoryBehavior,
276        target_snapshot_params: TargetSnapshotParams,
277    ) {
278        let browsing_context_id = match self.browsing_context_id() {
279            None => return warn!("Attempted to start a new pipeline on an unattached iframe."),
280            Some(id) => id,
281        };
282
283        let webview_id = match self.webview_id() {
284            None => return warn!("Attempted to start a new pipeline on an unattached iframe."),
285            Some(id) => id,
286        };
287
288        let window = self.owner_window();
289        let old_pipeline_id = self.pipeline_id();
290        let new_pipeline_id = PipelineId::new();
291        self.pending_pipeline_id.set(Some(new_pipeline_id));
292
293        let load_info = IFrameLoadInfo {
294            parent_pipeline_id: window.pipeline_id(),
295            browsing_context_id,
296            webview_id,
297            new_pipeline_id,
298            is_private: false, // FIXME
299            inherited_secure_context: load_data.inherited_secure_context,
300            history_handling,
301            target_snapshot_params,
302            name: self.frozen_name.borrow().clone(),
303        };
304
305        let viewport_details = window
306            .get_iframe_viewport_details_if_known(cx, browsing_context_id)
307            .unwrap_or_else(|| ViewportDetails {
308                hidpi_scale_factor: window.device_pixel_ratio(),
309                ..Default::default()
310            });
311
312        match pipeline_type {
313            PipelineType::InitialAboutBlank => {
314                self.about_blank_pipeline_id.set(Some(new_pipeline_id));
315
316                let load_info = IFrameLoadInfoWithData {
317                    info: load_info,
318                    load_data: load_data.clone(),
319                    old_pipeline_id,
320                    viewport_details,
321                };
322                window
323                    .as_global_scope()
324                    .script_to_constellation_chan()
325                    .send(ScriptToConstellationMessage::ScriptNewIFrame(load_info))
326                    .unwrap();
327
328                let new_pipeline_info = NewPipelineInfo {
329                    webview_state: (*window.webview_state()).clone(),
330                    parent_info: Some(window.pipeline_id()),
331                    new_pipeline_id,
332                    browsing_context_id,
333                    opener: None,
334                    load_data,
335                    viewport_details,
336                    user_content_manager_id: None,
337                    target_snapshot_params,
338                    frame_name: self.frozen_name.borrow().clone(),
339                };
340
341                self.pipeline_id.set(Some(new_pipeline_id));
342                with_script_thread(|script_thread| {
343                    script_thread.spawn_pipeline(cx, new_pipeline_info);
344                });
345            },
346            PipelineType::Navigation => {
347                let load_info = IFrameLoadInfoWithData {
348                    info: load_info,
349                    load_data,
350                    old_pipeline_id,
351                    viewport_details,
352                };
353                window
354                    .as_global_scope()
355                    .script_to_constellation_chan()
356                    .send(ScriptToConstellationMessage::ScriptLoadedURLInIFrame(
357                        load_info,
358                    ))
359                    .unwrap();
360            },
361        }
362    }
363
364    /// When an iframe is first inserted into the document,
365    /// an "about:blank" document is created,
366    /// and synchronously processed by the script thread.
367    /// This initial synchronous load should have no noticeable effect in script.
368    /// See the note in `iframe_load_event_steps`.
369    pub(crate) fn is_initial_blank_document(&self) -> bool {
370        self.pending_pipeline_id.get() == self.about_blank_pipeline_id.get()
371    }
372
373    /// <https://html.spec.whatwg.org/multipage/#navigate-an-iframe-or-frame>
374    fn navigate_an_iframe_or_frame(
375        &self,
376        cx: &mut JSContext,
377        load_data: LoadData,
378        mode: ProcessingMode,
379    ) {
380        // Step 2. If element's content navigable's active document is not completely loaded,
381        // then set historyHandling to "replace".
382        let history_handling = if !self
383            .GetContentDocument()
384            .is_some_and(|doc| doc.completely_loaded())
385        {
386            NavigationHistoryBehavior::Replace
387        } else {
388            // Step 1. Let historyHandling be "auto".
389            NavigationHistoryBehavior::Auto
390        };
391        // Step 3. If element is an iframe, then set element's pending resource-timing start time
392        // to the current high resolution time given element's node document's relevant global object.
393        // TODO
394
395        // Step 4. Navigate element's content navigable to url using element's node document,
396        // with historyHandling set to historyHandling, referrerPolicy set to referrerPolicy,
397        // documentResource set to srcdocString, and initialInsertion set to initialInsertion.
398        let target_snapshot_params = snapshot_self(self);
399        self.navigate_or_reload_child_browsing_context(
400            cx,
401            load_data,
402            history_handling,
403            mode,
404            target_snapshot_params,
405        );
406    }
407
408    /// <https://html.spec.whatwg.org/multipage/#will-lazy-load-element-steps>
409    fn will_lazy_load_element_steps(&self) -> bool {
410        // Step 1. If scripting is disabled for element, then return false.
411        if !self.owner_document().scripting_enabled() {
412            return false;
413        }
414        // Step 2. If element's lazy loading attribute is in the Lazy state, then return true.
415        // Step 3. Return false.
416        self.Loading() == "lazy"
417    }
418
419    /// Step 1.3. of <https://html.spec.whatwg.org/multipage/#process-the-iframe-attributes>
420    fn navigate_to_the_srcdoc_resource(&self, cx: &mut JSContext, mode: ProcessingMode) {
421        // Step 1.3. Navigate to the srcdoc resource: Navigate an iframe or frame given element,
422        // about:srcdoc, the empty string, and the value of element's srcdoc attribute.
423        let url = ServoUrl::parse("about:srcdoc").unwrap();
424        let document = self.owner_document();
425        let window = self.owner_window();
426        let pipeline_id = Some(window.pipeline_id());
427        let mut load_data = LoadData::new(
428            LoadOrigin::Script(document.origin().snapshot()),
429            url,
430            Some(document.base_url()),
431            pipeline_id,
432            window.as_global_scope().get_referrer(),
433            document.get_referrer_policy(),
434            Some(window.as_global_scope().is_secure_context()),
435            Some(document.insecure_requests_policy()),
436            window
437                .as_global_scope()
438                .upgrade_insecure_navigations_set()
439                .clone(),
440            document.has_trustworthy_ancestor_or_current_origin(),
441            self.sandboxing_flag_set(),
442        );
443        load_data.destination = Destination::IFrame;
444        load_data.policy_container = Some(window.as_global_scope().policy_container());
445        load_data.srcdoc = String::from(
446            self.upcast::<Element>()
447                .get_string_attribute(&local_name!("srcdoc")),
448        );
449
450        self.navigate_an_iframe_or_frame(cx, load_data, mode);
451    }
452
453    /// <https://html.spec.whatwg.org/multipage/#the-iframe-element:potentially-delays-the-load-event>
454    fn mark_navigation_as_lazy_loaded(&self, cx: &mut JSContext) {
455        // > An iframe element whose current navigation was lazy loaded boolean is false potentially delays the load event.
456        self.current_navigation_was_lazy_loaded.set(true);
457        let blocker = &self.load_blocker;
458        LoadBlocker::terminate(cx, blocker);
459    }
460
461    /// <https://html.spec.whatwg.org/multipage/#process-the-iframe-attributes>
462    fn process_the_iframe_attributes(&self, cx: &mut JSContext, mode: ProcessingMode) {
463        let element = self.upcast::<Element>();
464
465        // Step 1. If `element`'s `srcdoc` attribute is specified, then:
466        //
467        // Note that this also includes the empty string
468        if element.has_attribute(&local_name!("srcdoc")) {
469            // Step 1.1. Set element's current navigation was lazy loaded boolean to false.
470            self.current_navigation_was_lazy_loaded.set(false);
471            // Step 1.2. If the will lazy load element steps given element return true, then:
472            if self.will_lazy_load_element_steps() {
473                // Step 1.2.1. Set element's lazy load resumption steps to the rest of this algorithm
474                // starting with the step labeled navigate to the srcdoc resource.
475                self.lazy_load_resumption_steps
476                    .set(LazyLoadResumptionSteps::SrcDoc);
477                // Step 1.2.2. Set element's current navigation was lazy loaded boolean to true.
478                self.mark_navigation_as_lazy_loaded(cx);
479                // Step 1.2.3. Start intersection-observing a lazy loading element for element.
480                self.owner_document()
481                    .start_intersection_observing_a_lazy_loading_element(
482                        cx,
483                        self.upcast::<Element>(),
484                    );
485                // Step 1.2.4. Return.
486                return;
487            }
488            // Step 1.3. Navigate to the srcdoc resource: Navigate an iframe or frame given element,
489            // about:srcdoc, the empty string, and the value of element's srcdoc attribute.
490            self.navigate_to_the_srcdoc_resource(cx, mode);
491            return;
492        }
493
494        let window = self.owner_window();
495
496        // Step 2.1. Let url be the result of running the shared attribute processing steps
497        // for iframe and frame elements given element and initialInsertion.
498        let Some(url) = self.shared_attribute_processing_steps_for_iframe_and_frame_elements(mode)
499        else {
500            // Step 2.2. If url is null, then return.
501            return;
502        };
503
504        // Step 2.3. If url matches about:blank and initialInsertion is true, then:
505        if url.matches_about_blank() && mode == ProcessingMode::FirstTime {
506            // Step 2.3.1. Run the iframe load event steps given element.
507            self.run_iframe_load_event_steps(cx);
508            // Step 2.3.2. Return.
509            return;
510        }
511
512        // Step 2.4: Let referrerPolicy be the current state of element's referrerpolicy content
513        // attribute.
514        let document = self.owner_document();
515        let referrer_policy_token = self.ReferrerPolicy();
516
517        // Note: despite not being explicitly stated in the spec steps, this falls back to
518        // document's referrer policy here because it satisfies the expectations that when unset,
519        // the iframe should inherit the referrer policy of its parent
520        let referrer_policy = match ReferrerPolicy::from(&*referrer_policy_token.str()) {
521            ReferrerPolicy::EmptyString => document.get_referrer_policy(),
522            policy => policy,
523        };
524
525        // TODO(#25748):
526        // By spec, we return early if there's an ancestor browsing context
527        // "whose active document's url, ignoring fragments, is equal".
528        // However, asking about ancestor browsing contexts is more nuanced than
529        // it sounds and not implemented here.
530        // Within a single origin, we can do it by walking window proxies,
531        // and this check covers only that single-origin case, protecting
532        // against simple typo self-includes but nothing more elaborate.
533        let mut ancestor = window.GetParent();
534        while let Some(a) = ancestor {
535            if let Some(ancestor_url) = a.document().map(|d| d.url()) &&
536                ancestor_url.scheme() == url.scheme() &&
537                ancestor_url.username() == url.username() &&
538                ancestor_url.password() == url.password() &&
539                ancestor_url.host() == url.host() &&
540                ancestor_url.port() == url.port() &&
541                ancestor_url.path() == url.path() &&
542                ancestor_url.query() == url.query()
543            {
544                return;
545            }
546            ancestor = a.parent().map(DomRoot::from_ref);
547        }
548
549        let (creator_pipeline_id, about_base_url) = if url.matches_about_blank() {
550            (Some(window.pipeline_id()), Some(document.base_url()))
551        } else {
552            (None, document.about_base_url())
553        };
554
555        let propagate_encoding_to_child_document = url.origin().same_origin(&window.origin());
556        let mut load_data = LoadData::new(
557            LoadOrigin::Script(document.origin().snapshot()),
558            url,
559            about_base_url,
560            creator_pipeline_id,
561            window.as_global_scope().get_referrer(),
562            referrer_policy,
563            Some(window.as_global_scope().is_secure_context()),
564            Some(document.insecure_requests_policy()),
565            window
566                .as_global_scope()
567                .upgrade_insecure_navigations_set()
568                .clone(),
569            document.has_trustworthy_ancestor_or_current_origin(),
570            self.sandboxing_flag_set(),
571        );
572        load_data.destination = Destination::IFrame;
573        load_data.policy_container = Some(window.as_global_scope().policy_container());
574        if propagate_encoding_to_child_document {
575            load_data.container_document_encoding = Some(document.encoding());
576        }
577
578        let pipeline_id = self.pipeline_id();
579        // If the initial `about:blank` page is the current page, load with replacement enabled,
580        // see https://html.spec.whatwg.org/multipage/#the-iframe-element:about:blank-3
581        let is_about_blank =
582            pipeline_id.is_some() && pipeline_id == self.about_blank_pipeline_id.get();
583
584        let history_handling = if is_about_blank {
585            NavigationHistoryBehavior::Replace
586        } else {
587            NavigationHistoryBehavior::Push
588        };
589
590        let target_snapshot_params = snapshot_self(self);
591        self.navigate_or_reload_child_browsing_context(
592            cx,
593            load_data,
594            history_handling,
595            mode,
596            target_snapshot_params,
597        );
598    }
599
600    /// <https://html.spec.whatwg.org/multipage/#create-a-new-child-navigable>
601    /// Synchronously create a new browsing context; this is not a navigation.
602    fn create_nested_browsing_context(&self, cx: &mut JSContext) {
603        // Step 1. Let parentNavigable be element's node navigable.
604        let document = self.owner_document();
605        let window = self.owner_window();
606        let pipeline_id = Some(window.pipeline_id());
607        // Step 4. Let targetName be null.
608        // Step 5. If element has a name content attribute,
609        // then set targetName to the value of that attribute.
610        *self.frozen_name.borrow_mut() = self
611            .upcast::<Element>()
612            .get_name()
613            .map(|name| name.to_string());
614        // Step 6. Let documentState be a new document state, with
615        let mut load_data = LoadData::new(
616            // > initiator origin
617            // >     document's origin
618            LoadOrigin::Script(document.origin().snapshot()),
619            ServoUrl::parse("about:blank").unwrap(),
620            // > about base URL
621            // >     document's about base URL
622            Some(document.base_url()),
623            pipeline_id,
624            window.as_global_scope().get_referrer(),
625            document.get_referrer_policy(),
626            Some(window.as_global_scope().is_secure_context()),
627            Some(document.insecure_requests_policy()),
628            window
629                .as_global_scope()
630                .upgrade_insecure_navigations_set()
631                .clone(),
632            document.has_trustworthy_ancestor_or_current_origin(),
633            self.sandboxing_flag_set(),
634        );
635        load_data.is_initial_about_blank = true;
636        load_data.destination = Destination::IFrame;
637        load_data.policy_container = Some(window.as_global_scope().policy_container());
638
639        // Step 7. Let navigable be a new navigable.
640        let browsing_context_id = BrowsingContextId::new();
641        let webview_id = window.window_proxy().webview_id();
642        self.pipeline_id.set(None);
643        self.pending_pipeline_id.set(None);
644        self.webview_id.set(Some(webview_id));
645        self.browsing_context_id.set(Some(browsing_context_id));
646        // Step 8. Initialize the navigable navigable given documentState and parentNavigable.
647        self.start_new_pipeline(
648            cx,
649            load_data,
650            PipelineType::InitialAboutBlank,
651            NavigationHistoryBehavior::Push,
652            ProcessingMode::FirstTime,
653            snapshot_self(self),
654        );
655        // > navigable target name
656        // >     targetName
657        if let Some(window) = self.GetContentWindow() &&
658            let Some(window_name) = &*self.frozen_name.borrow()
659        {
660            window.set_name(window_name.as_str().into());
661        }
662    }
663
664    fn destroy_nested_browsing_context(&self) {
665        self.pipeline_id.set(None);
666        self.pending_pipeline_id.set(None);
667        self.about_blank_pipeline_id.set(None);
668        self.webview_id.set(None);
669        if let Some(browsing_context_id) = self.browsing_context_id.take() {
670            self.script_window_proxies.remove(browsing_context_id)
671        }
672    }
673
674    /// Returns true if the contained pipeline was updated, false otherwise.
675    /// This can occur if the iframe's nested browsing context has changed
676    /// since the asynchronous update was started.
677    pub(crate) fn update_pipeline_id(
678        &self,
679        cx: &mut JSContext,
680        new_pipeline_id: PipelineId,
681        reason: UpdatePipelineIdReason,
682    ) -> bool {
683        // For all updates except the one for the initial blank document,
684        // we need to set the flag back to false because the navigation is complete,
685        // because the goal is to, when a navigation is pending, to skip the async load
686        // steps of the initial blank document.
687        if !self.is_initial_blank_document() {
688            self.pending_navigation.set(false);
689        }
690        if self.pending_pipeline_id.get() != Some(new_pipeline_id) &&
691            reason == UpdatePipelineIdReason::Navigation
692        {
693            return false;
694        }
695
696        self.pipeline_id.set(Some(new_pipeline_id));
697
698        // Only terminate the load blocker if the pipeline id was updated due to a traversal.
699        // The load blocker will be terminated for a navigation in iframe_load_event_steps.
700        if reason == UpdatePipelineIdReason::Traversal {
701            let blocker = &self.load_blocker;
702            LoadBlocker::terminate(cx, blocker);
703        }
704
705        self.upcast::<Node>().dirty(cx.no_gc(), NodeDamage::Other);
706        true
707    }
708
709    fn new_inherited(
710        local_name: LocalName,
711        prefix: Option<Prefix>,
712        document: &Document,
713    ) -> HTMLIFrameElement {
714        HTMLIFrameElement {
715            htmlelement: HTMLElement::new_inherited(local_name, prefix, document),
716            browsing_context_id: Cell::new(None),
717            webview_id: Cell::new(None),
718            pipeline_id: Cell::new(None),
719            pending_pipeline_id: Cell::new(None),
720            about_blank_pipeline_id: Cell::new(None),
721            sandbox: Default::default(),
722            sandboxing_flag_set: Cell::new(None),
723            load_blocker: DomRefCell::new(None),
724            script_window_proxies: ScriptThread::window_proxies(),
725            current_navigation_was_lazy_loaded: Default::default(),
726            lazy_load_resumption_steps: Default::default(),
727            pending_navigation: Default::default(),
728            frozen_name: Default::default(),
729        }
730    }
731
732    pub(crate) fn new(
733        cx: &mut JSContext,
734        local_name: LocalName,
735        prefix: Option<Prefix>,
736        document: &Document,
737        proto: Option<HandleObject>,
738    ) -> DomRoot<HTMLIFrameElement> {
739        Node::reflect_node_with_proto(
740            cx,
741            Box::new(HTMLIFrameElement::new_inherited(
742                local_name, prefix, document,
743            )),
744            document,
745            proto,
746        )
747    }
748
749    #[inline]
750    pub(crate) fn pipeline_id(&self) -> Option<PipelineId> {
751        self.pipeline_id.get()
752    }
753
754    #[inline]
755    pub(crate) fn browsing_context_id(&self) -> Option<BrowsingContextId> {
756        self.browsing_context_id.get()
757    }
758
759    #[inline]
760    pub(crate) fn webview_id(&self) -> Option<WebViewId> {
761        self.webview_id.get()
762    }
763
764    #[inline]
765    pub(crate) fn sandboxing_flag_set(&self) -> SandboxingFlagSet {
766        self.sandboxing_flag_set
767            .get()
768            .unwrap_or_else(SandboxingFlagSet::empty)
769    }
770
771    /// Note a pending navigation.
772    /// This is used to ignore the async load event steps for
773    /// the initial blank document if those haven't run yet.
774    pub(crate) fn note_pending_navigation(&self) {
775        self.pending_navigation.set(true);
776    }
777
778    /// The load for this `<iframe>` has finished. This may or may not trigger the
779    /// `<iframe>` load event steps depending on whether or not the load was aborted
780    /// or if it's an initial `about:blank` load.
781    pub(crate) fn load_finished(
782        &self,
783        cx: &mut JSContext,
784        loaded_pipeline: PipelineId,
785        aborted: bool,
786    ) {
787        // TODO(#9592): assert that the load blocker is present at all times when we
788        //              can guarantee that it's created for the case of iframe.reload().
789        if Some(loaded_pipeline) != self.pending_pipeline_id.get() {
790            return;
791        }
792
793        // We never execute the loading steps when a load is aborted, but we still must
794        // stop blocking the load on this `<iframe>`.
795        if aborted {
796            let blocker = &self.load_blocker;
797            LoadBlocker::terminate(cx, blocker);
798            return;
799        }
800
801        // TODO 1. Assert: element's content navigable is not null.
802
803        // TODO 2-4 Mark resource timing.
804
805        // TODO 5 Set childDocument's iframe load in progress flag.
806
807        // Note: in the spec, these steps are either run synchronously as part of
808        // "If url matches about:blank and initialInsertion is true, then:"
809        // in `process the iframe attributes`,
810        // or asynchronously when navigation completes.
811        //
812        // In our current implementation,
813        // we arrive here always asynchronously in the following two cases:
814        // 1. as part of loading the initial blank document
815        //    created in `create_nested_browsing_context`
816        // 2. optionally, as part of loading a second document created as
817        //    as part of the first processing of the iframe attributes.
818        //
819        // To preserve the logic of the spec--firing the load event once--in the context of
820        // our current implementation, we must not fire the load event
821        // for the initial blank document if we know that a navigation is ongoing,
822        // which can be deducted from `pending_navigation` or the presence of an src.
823        //
824        // Additionally, to prevent a race condition with navigations,
825        // in all cases, skip the load event if there is a pending navigation.
826        // See #40348
827        //
828        // TODO: run these step synchronously as part of processing the iframe attributes.
829        let should_fire_event = if self.is_initial_blank_document() {
830            // If this is the initial blank doc:
831            // do not fire if there is a pending navigation,
832            // or if the iframe has an src.
833            !self.pending_navigation.get() &&
834                !self.upcast::<Element>().has_attribute(&local_name!("src"))
835        } else {
836            // If this is not the initial blank doc:
837            // do not fire if there is a pending navigation.
838            !self.pending_navigation.get()
839        };
840
841        if should_fire_event {
842            self.run_iframe_load_event_steps(cx);
843        } else {
844            debug!(
845                "suppressing load event for iframe, loaded {:?}",
846                loaded_pipeline
847            );
848        }
849    }
850
851    /// <https://html.spec.whatwg.org/multipage/#iframe-load-event-steps>
852    pub(crate) fn run_iframe_load_event_steps(&self, cx: &mut JSContext) {
853        // TODO 1. Assert: element's content navigable is not null.
854
855        // Step 2. Let childDocument be element's content navigable's active document.
856        let child_document = self.GetContentDocument();
857
858        // Step 3. If childDocument has its mute iframe load flag set, then return.
859        // Step 5. Set childDocument's iframe load in progress flag.
860        if let Some(document) = child_document {
861            if document.mute_iframe_load_flag() {
862                let blocker = &self.load_blocker;
863                LoadBlocker::terminate(cx, blocker);
864                return;
865            }
866            document.set_iframe_load_in_progress(true);
867        }
868
869        // Step 4. If element's pending resource-timing start time is not null, then:
870        // TODO
871
872        // Step 6. Fire an event named load at element.
873        self.upcast::<EventTarget>().fire_event(cx, atom!("load"));
874
875        let blocker = &self.load_blocker;
876        LoadBlocker::terminate(cx, blocker);
877
878        // Step 7. Unset childDocument's iframe load in progress flag
879        if let Some(child_document) = self.GetContentDocument() {
880            child_document.set_iframe_load_in_progress(false);
881        }
882    }
883
884    /// Parse the `sandbox` attribute value given the [`Attr`]. This sets the `sandboxing_flag_set`
885    /// property or clears it is the value isn't specified. Notably, an unspecified sandboxing
886    /// attribute (no sandboxing) is different from an empty one (full sandboxing).
887    fn parse_sandbox_attribute(&self) {
888        let sandbox_value =
889            self.upcast::<Element>()
890                .with_attribute(&ns!(), &local_name!("sandbox"), |attribute| {
891                    let tokens: Vec<_> = attribute
892                        .value()
893                        .as_tokens()
894                        .iter()
895                        .map(|atom| atom.to_ascii_lowercase().to_string())
896                        .collect();
897                    parse_a_sandboxing_directive(&tokens)
898                });
899        self.sandboxing_flag_set.set(sandbox_value);
900    }
901
902    /// Step 4.2. of <https://html.spec.whatwg.org/multipage/#destroy-a-document-and-its-descendants>
903    pub(crate) fn destroy_document_and_its_descendants(&self, cx: &mut JSContext) {
904        let Some(pipeline_id) = self.pipeline_id.get() else {
905            return;
906        };
907        // Step 4.2. Destroy a document and its descendants given childNavigable's active document and incrementDestroyed.
908        if let Some(exited_document) = ScriptThread::find_document(pipeline_id) {
909            exited_document.destroy_document_and_its_descendants(cx);
910        }
911        self.destroy_nested_browsing_context();
912    }
913
914    /// <https://html.spec.whatwg.org/multipage/#destroy-a-child-navigable>
915    fn destroy_child_navigable(&self, cx: &mut JSContext) {
916        let blocker = &self.load_blocker;
917        LoadBlocker::terminate(cx, blocker);
918
919        // Step 1. Let navigable be container's content navigable.
920        let Some(browsing_context_id) = self.browsing_context_id() else {
921            // Step 2. If navigable is null, then return.
922            return;
923        };
924        // Store now so that we can destroy the context and delete the
925        // document later
926        let pipeline_id = self.pipeline_id.get();
927
928        // Step 3. Set container's content navigable to null.
929        //
930        // Resetting the pipeline_id to None is required here so that
931        // if this iframe is subsequently re-added to the document
932        // the load doesn't think that it's a navigation, but instead
933        // a new iframe. Without this, the constellation gets very
934        // confused.
935        self.destroy_nested_browsing_context();
936
937        // Step 4. Inform the navigation API about child navigable destruction given navigable.
938        // TODO
939
940        // Step 5. Destroy a document and its descendants given navigable's active document.
941        let (sender, receiver) = channel(self.global().time_profiler_chan().clone()).unwrap();
942        let msg = ScriptToConstellationMessage::RemoveIFrame(browsing_context_id, sender);
943        self.owner_window()
944            .as_global_scope()
945            .script_to_constellation_chan()
946            .send(msg)
947            .unwrap();
948        let _exited_pipeline_ids = receiver.recv().unwrap();
949        let Some(pipeline_id) = pipeline_id else {
950            return;
951        };
952        if let Some(exited_document) = ScriptThread::find_document(pipeline_id) {
953            exited_document.destroy_document_and_its_descendants(cx);
954        }
955
956        // Step 6. Let parentDocState be container's node navigable's active session history entry's document state.
957        // TODO
958
959        // Step 7. Remove the nested history from parentDocState's nested histories whose id equals navigable's id.
960        // TODO
961
962        // Step 8. Let traversable be container's node navigable's traversable navigable.
963        // TODO
964
965        // Step 9. Append the following session history traversal steps to traversable:
966        // TODO
967
968        // Step 10. Invoke WebDriver BiDi navigable destroyed with navigable.
969        // TODO
970    }
971}
972
973impl LayoutDom<'_, HTMLIFrameElement> {
974    #[inline]
975    pub(crate) fn pipeline_id(self) -> Option<PipelineId> {
976        (self.unsafe_get()).pipeline_id.get()
977    }
978
979    #[inline]
980    pub(crate) fn browsing_context_id(self) -> Option<BrowsingContextId> {
981        (self.unsafe_get()).browsing_context_id.get()
982    }
983
984    pub(crate) fn width(self) -> LengthOrPercentageOrAuto {
985        self.upcast::<Element>()
986            .get_attr_for_layout(&ns!(), &local_name!("width"))
987            .map(AttrValue::as_dimension)
988            .cloned()
989            .unwrap_or(LengthOrPercentageOrAuto::Auto)
990    }
991
992    pub(crate) fn height(self) -> LengthOrPercentageOrAuto {
993        self.upcast::<Element>()
994            .get_attr_for_layout(&ns!(), &local_name!("height"))
995            .map(AttrValue::as_dimension)
996            .cloned()
997            .unwrap_or(LengthOrPercentageOrAuto::Auto)
998    }
999}
1000
1001impl HTMLIFrameElementMethods<crate::DomTypeHolder> for HTMLIFrameElement {
1002    // https://html.spec.whatwg.org/multipage/#dom-iframe-src
1003    make_url_getter!(Src, "src");
1004
1005    // https://html.spec.whatwg.org/multipage/#dom-iframe-src
1006    make_url_setter!(SetSrc, "src");
1007
1008    /// <https://html.spec.whatwg.org/multipage/#dom-iframe-srcdoc>
1009    fn Srcdoc(&self) -> TrustedHTMLOrString {
1010        let element = self.upcast::<Element>();
1011        element.get_trusted_html_attribute(&local_name!("srcdoc"))
1012    }
1013
1014    /// <https://html.spec.whatwg.org/multipage/#dom-iframe-srcdoc>
1015    fn SetSrcdoc(&self, cx: &mut JSContext, value: TrustedHTMLOrString) -> Fallible<()> {
1016        // Step 1: Let compliantString be the result of invoking the
1017        // Get Trusted Type compliant string algorithm with TrustedHTML,
1018        // this's relevant global object, the given value, "HTMLIFrameElement srcdoc", and "script".
1019        let element = self.upcast::<Element>();
1020        let value = TrustedHTML::get_trusted_type_compliant_string(
1021            cx,
1022            &element.owner_global(),
1023            value,
1024            "HTMLIFrameElement srcdoc",
1025        )?;
1026        // Step 2: Set an attribute value given this, srcdoc's local name, and compliantString.
1027        element.set_attribute(
1028            cx,
1029            &local_name!("srcdoc"),
1030            AttrValue::String(value.str().to_owned()),
1031        );
1032        Ok(())
1033    }
1034
1035    /// <https://html.spec.whatwg.org/multipage/#dom-iframe-sandbox>
1036    ///
1037    /// The supported tokens for sandbox's DOMTokenList are the allowed values defined in the
1038    /// sandbox attribute and supported by the user agent. These range of possible values is
1039    /// defined here: <https://html.spec.whatwg.org/multipage/#attr-iframe-sandbox>
1040    fn Sandbox(&self, cx: &mut JSContext) -> DomRoot<DOMTokenList> {
1041        self.sandbox.or_init(|| {
1042            DOMTokenList::new(
1043                cx,
1044                self.upcast::<Element>(),
1045                &local_name!("sandbox"),
1046                Some(vec![
1047                    Atom::from("allow-downloads"),
1048                    Atom::from("allow-forms"),
1049                    Atom::from("allow-modals"),
1050                    Atom::from("allow-orientation-lock"),
1051                    Atom::from("allow-pointer-lock"),
1052                    Atom::from("allow-popups"),
1053                    Atom::from("allow-popups-to-escape-sandbox"),
1054                    Atom::from("allow-presentation"),
1055                    Atom::from("allow-same-origin"),
1056                    Atom::from("allow-scripts"),
1057                    Atom::from("allow-top-navigation"),
1058                    Atom::from("allow-top-navigation-by-user-activation"),
1059                    Atom::from("allow-top-navigation-to-custom-protocols"),
1060                ]),
1061            )
1062        })
1063    }
1064
1065    /// <https://html.spec.whatwg.org/multipage/#dom-iframe-contentwindow>
1066    fn GetContentWindow(&self) -> Option<DomRoot<WindowProxy>> {
1067        self.browsing_context_id
1068            .get()
1069            .and_then(|id| self.script_window_proxies.find_window_proxy(id))
1070    }
1071
1072    /// <https://html.spec.whatwg.org/multipage/#concept-bcc-content-document>
1073    fn GetContentDocument(&self) -> Option<DomRoot<Document>> {
1074        // Step 1. If container's content navigable is null, then return null.
1075        let pipeline_id = self.pipeline_id.get()?;
1076
1077        // Step 2. Let document be container's content navigable's active document.
1078        // Note that this lookup will fail if the document is dissimilar-origin,
1079        // so we should return None in that case.
1080        let document = ScriptThread::find_document(pipeline_id)?;
1081        // Step 3. If document's origin and container's node document's origin are not same origin-domain, then return null.
1082        if !self
1083            .owner_document()
1084            .origin()
1085            .same_origin_domain(&document.origin())
1086        {
1087            return None;
1088        }
1089        // Step 4. Return document.
1090        Some(document)
1091    }
1092
1093    /// <https://html.spec.whatwg.org/multipage/#attr-iframe-referrerpolicy>
1094    fn ReferrerPolicy(&self) -> DOMString {
1095        reflect_referrer_policy_attribute(self.upcast::<Element>())
1096    }
1097
1098    // https://html.spec.whatwg.org/multipage/#attr-iframe-referrerpolicy
1099    make_setter!(SetReferrerPolicy, "referrerpolicy");
1100
1101    // https://html.spec.whatwg.org/multipage/#attr-iframe-allowfullscreen
1102    make_bool_getter!(AllowFullscreen, "allowfullscreen");
1103    // https://html.spec.whatwg.org/multipage/#attr-iframe-allowfullscreen
1104    make_bool_setter!(SetAllowFullscreen, "allowfullscreen");
1105
1106    // <https://html.spec.whatwg.org/multipage/#dom-dim-width>
1107    make_getter!(Width, "width");
1108    // <https://html.spec.whatwg.org/multipage/#dom-dim-width>
1109    make_dimension_setter!(SetWidth, "width");
1110
1111    // <https://html.spec.whatwg.org/multipage/#dom-dim-height>
1112    make_getter!(Height, "height");
1113    // <https://html.spec.whatwg.org/multipage/#dom-dim-height>
1114    make_dimension_setter!(SetHeight, "height");
1115
1116    // https://html.spec.whatwg.org/multipage/#other-elements,-attributes-and-apis:attr-iframe-frameborder
1117    make_getter!(FrameBorder, "frameborder");
1118    // https://html.spec.whatwg.org/multipage/#other-elements,-attributes-and-apis:attr-iframe-frameborder
1119    make_setter!(SetFrameBorder, "frameborder");
1120
1121    // https://html.spec.whatwg.org/multipage/#dom-iframe-name
1122    // A child browsing context checks the name of its iframe only at the time
1123    // it is created; subsequent name sets have no special effect.
1124    make_atomic_setter!(SetName, "name");
1125
1126    // https://html.spec.whatwg.org/multipage/#dom-iframe-name
1127    // This is specified as reflecting the name content attribute of the
1128    // element, not the name of the child browsing context.
1129    make_getter!(Name, "name");
1130
1131    // https://html.spec.whatwg.org/multipage/#attr-iframe-loading
1132    // > The loading attribute is a lazy loading attribute. Its purpose is to indicate the policy for loading iframe elements that are outside the viewport.
1133    make_enumerated_getter!(
1134        Loading,
1135        "loading",
1136        "lazy" | "eager",
1137        // https://html.spec.whatwg.org/multipage/#lazy-loading-attribute
1138        // > The attribute's missing value default and invalid value default are both the Eager state.
1139        missing => "eager",
1140        invalid => "eager"
1141    );
1142
1143    // https://html.spec.whatwg.org/multipage/#attr-iframe-loading
1144    make_setter!(SetLoading, "loading");
1145
1146    // https://html.spec.whatwg.org/multipage/#dom-iframe-longdesc
1147    make_url_getter!(LongDesc, "longdesc");
1148
1149    // https://html.spec.whatwg.org/multipage/#dom-iframe-longdesc
1150    make_url_setter!(SetLongDesc, "longdesc");
1151}
1152
1153impl VirtualMethods for HTMLIFrameElement {
1154    fn super_type(&self) -> Option<&dyn VirtualMethods> {
1155        Some(self.upcast::<HTMLElement>() as &dyn VirtualMethods)
1156    }
1157
1158    fn attribute_mutated(
1159        &self,
1160        cx: &mut JSContext,
1161        attr: AttrRef<'_>,
1162        mutation: AttributeMutation,
1163    ) {
1164        self.super_type()
1165            .unwrap()
1166            .attribute_mutated(cx, attr, mutation);
1167        match *attr.local_name() {
1168            // From <https://html.spec.whatwg.org/multipage/#attr-iframe-sandbox>:
1169            //
1170            // > When an iframe element's sandbox attribute is set or changed while
1171            // > it has a non-null content navigable, the user agent must parse the
1172            // > sandboxing directive given the attribute's value and the iframe
1173            // > element's iframe sandboxing flag set.
1174            //
1175            // > When an iframe element's sandbox attribute is removed while it has
1176            // > a non-null content navigable, the user agent must empty the iframe
1177            // > element's iframe sandboxing flag set.
1178            local_name!("sandbox") if self.browsing_context_id.get().is_some() => {
1179                self.parse_sandbox_attribute();
1180            },
1181            local_name!("srcdoc") => {
1182                // https://html.spec.whatwg.org/multipage/#the-iframe-element:the-iframe-element-9
1183                // "Whenever an iframe element with a non-null nested browsing context has its
1184                // srcdoc attribute set, changed, or removed, the user agent must process the
1185                // iframe attributes."
1186                // but we can't check that directly, since the child browsing context
1187                // may be in a different script thread. Instead, we check to see if the parent
1188                // is in a document tree and has a browsing context, which is what causes
1189                // the child browsing context to be created.
1190
1191                // trigger the processing of iframe attributes whenever "srcdoc" attribute is set, changed or removed
1192                if self
1193                    .upcast::<Node>()
1194                    .is_connected_with_browsing_context(cx.no_gc())
1195                {
1196                    debug!("iframe srcdoc modified while in browsing context.");
1197                    self.process_the_iframe_attributes(cx, ProcessingMode::NotFirstTime);
1198                }
1199            },
1200            local_name!("src") => {
1201                // https://html.spec.whatwg.org/multipage/#the-iframe-element
1202                // "Similarly, whenever an iframe element with a non-null nested browsing context
1203                // but with no srcdoc attribute specified has its src attribute set, changed, or removed,
1204                // the user agent must process the iframe attributes,"
1205                // but we can't check that directly, since the child browsing context
1206                // may be in a different script thread. Instead, we check to see if the parent
1207                // is in a document tree and has a browsing context, which is what causes
1208                // the child browsing context to be created.
1209                if self
1210                    .upcast::<Node>()
1211                    .is_connected_with_browsing_context(cx.no_gc())
1212                {
1213                    debug!("iframe src set while in browsing context.");
1214                    self.process_the_iframe_attributes(cx, ProcessingMode::NotFirstTime);
1215                }
1216            },
1217            local_name!("loading") => {
1218                // https://html.spec.whatwg.org/multipage/#attr-iframe-loading
1219                // > When the loading attribute's state is changed to the Eager state, the user agent must run these steps:
1220                if !mutation.is_removal() && &**attr.value() == "lazy" {
1221                    return;
1222                }
1223
1224                // Steps 1-4. Take the lazy load resumption steps, return if there
1225                // are none, otherwise set them to null and invoke them.
1226                self.resume_lazy_load(cx);
1227            },
1228            _ => {},
1229        }
1230    }
1231
1232    fn attribute_affects_presentational_hints(&self, attr: AttrRef<'_>) -> bool {
1233        match attr.local_name() {
1234            &local_name!("width") | &local_name!("height") => true,
1235            _ => self
1236                .super_type()
1237                .unwrap()
1238                .attribute_affects_presentational_hints(attr),
1239        }
1240    }
1241
1242    fn parse_plain_attribute(&self, name: &LocalName, value: DOMString) -> AttrValue {
1243        match *name {
1244            local_name!("sandbox") => AttrValue::from_serialized_tokenlist(value.into()),
1245            local_name!("width") => AttrValue::from_dimension(value.into()),
1246            local_name!("height") => AttrValue::from_dimension(value.into()),
1247            _ => self
1248                .super_type()
1249                .unwrap()
1250                .parse_plain_attribute(name, value),
1251        }
1252    }
1253
1254    /// <https://html.spec.whatwg.org/multipage/#the-iframe-element:html-element-post-connection-steps>
1255    fn post_connection_steps(&self, cx: &mut JSContext) {
1256        if let Some(s) = self.super_type() {
1257            s.post_connection_steps(cx);
1258        }
1259
1260        // This isn't mentioned any longer in the specification, but still seems important. This is
1261        // likely due to the fact that we have deviated a great deal with it comes to navigables
1262        // and browsing contexts.
1263        if !self
1264            .upcast::<Node>()
1265            .is_connected_with_browsing_context(cx.no_gc())
1266        {
1267            return;
1268        }
1269
1270        debug!("<iframe> running post connection steps");
1271
1272        // Step 1: If insertedNode has a sandbox attribute, then parse the sandboxing directive
1273        // given the attribute's value and insertedNode's iframe sandboxing flag set.
1274        self.parse_sandbox_attribute();
1275
1276        // Step 2. Create a new child navigable for insertedNode.
1277        self.create_nested_browsing_context(cx);
1278
1279        // Step 3. Process the iframe attributes for insertedNode, with initialInsertion set to true.
1280        self.process_the_iframe_attributes(cx, ProcessingMode::FirstTime);
1281    }
1282
1283    fn bind_to_tree(&self, cx: &mut JSContext, context: &BindContext) {
1284        if let Some(super_type) = self.super_type() {
1285            super_type.bind_to_tree(cx, context);
1286        }
1287
1288        self.owner_document().iframes().add(cx.no_gc(), self);
1289    }
1290
1291    /// <https://html.spec.whatwg.org/multipage/#the-iframe-element:html-element-removing-steps>
1292    fn unbind_from_tree(&self, cx: &mut JSContext, context: &UnbindContext) {
1293        if let Some(super_type) = self.super_type() {
1294            super_type.unbind_from_tree(cx, context);
1295        }
1296
1297        // The iframe HTML element removing steps, given removedNode, are to destroy a child
1298        // navigable given removedNode
1299        self.destroy_child_navigable(cx);
1300
1301        self.owner_document().iframes().remove(cx.no_gc(), self);
1302    }
1303}
1304
1305/// IframeContext is a wrapper around [`HTMLIFrameElement`] that implements the
1306/// [`ResourceTimingListener`] trait.
1307pub(crate) struct IframeContext {
1308    // The URL of the iframe document.
1309    url: ServoUrl,
1310}
1311
1312impl IframeContext {
1313    /// Creates a new IframeContext from a reference to an HTMLIFrameElement.
1314    pub fn new(element: &HTMLIFrameElement) -> Self {
1315        Self {
1316            url: element
1317                .shared_attribute_processing_steps_for_iframe_and_frame_elements(
1318                    ProcessingMode::NotFirstTime,
1319                )
1320                .expect("Must always have a URL when navigating"),
1321        }
1322    }
1323}
1324
1325impl ResourceTimingListener for IframeContext {
1326    fn resource_timing_information(&self) -> (InitiatorType, ServoUrl) {
1327        (InitiatorType::LocalName("iframe".into()), self.url.clone())
1328    }
1329}
1330
1331fn snapshot_self(iframe: &HTMLIFrameElement) -> TargetSnapshotParams {
1332    let child_navigable = iframe.GetContentWindow();
1333    TargetSnapshotParams {
1334        sandboxing_flags: determine_creation_sandboxing_flags(
1335            child_navigable.as_deref(),
1336            Some(iframe.upcast()),
1337        ),
1338        iframe_element_referrer_policy: determine_iframe_element_referrer_policy(Some(
1339            iframe.upcast(),
1340        )),
1341    }
1342}