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