1use 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#[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 current_navigation_was_lazy_loaded: Cell<bool>,
99 #[no_trace]
101 lazy_load_resumption_steps: Cell<LazyLoadResumptionSteps>,
102 pending_navigation: Cell<bool>,
109 frozen_name: DomRefCell<Option<String>>,
114}
115
116impl HTMLIFrameElement {
117 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 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 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 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 self.owner_document().encoding_parse_a_url(&url).ok()
156 }
157 })
158 .unwrap_or_else(|| ServoUrl::parse("about:blank").unwrap());
160 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 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 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 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 !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, 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 pub(crate) fn is_initial_blank_document(&self) -> bool {
370 self.pending_pipeline_id.get() == self.about_blank_pipeline_id.get()
371 }
372
373 fn navigate_an_iframe_or_frame(
375 &self,
376 cx: &mut JSContext,
377 load_data: LoadData,
378 mode: ProcessingMode,
379 ) {
380 let history_handling = if !self
383 .GetContentDocument()
384 .is_some_and(|doc| doc.completely_loaded())
385 {
386 NavigationHistoryBehavior::Replace
387 } else {
388 NavigationHistoryBehavior::Auto
390 };
391 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 fn will_lazy_load_element_steps(&self) -> bool {
410 if !self.owner_document().scripting_enabled() {
412 return false;
413 }
414 self.Loading() == "lazy"
417 }
418
419 fn navigate_to_the_srcdoc_resource(&self, cx: &mut JSContext, mode: ProcessingMode) {
421 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 fn mark_navigation_as_lazy_loaded(&self, cx: &mut JSContext) {
455 self.current_navigation_was_lazy_loaded.set(true);
457 let blocker = &self.load_blocker;
458 LoadBlocker::terminate(cx, blocker);
459 }
460
461 fn process_the_iframe_attributes(&self, cx: &mut JSContext, mode: ProcessingMode) {
463 let element = self.upcast::<Element>();
464
465 if element.has_attribute(&local_name!("srcdoc")) {
469 self.current_navigation_was_lazy_loaded.set(false);
471 if self.will_lazy_load_element_steps() {
473 self.lazy_load_resumption_steps
476 .set(LazyLoadResumptionSteps::SrcDoc);
477 self.mark_navigation_as_lazy_loaded(cx);
479 self.owner_document()
481 .start_intersection_observing_a_lazy_loading_element(
482 cx,
483 self.upcast::<Element>(),
484 );
485 return;
487 }
488 self.navigate_to_the_srcdoc_resource(cx, mode);
491 return;
492 }
493
494 let window = self.owner_window();
495
496 let Some(url) = self.shared_attribute_processing_steps_for_iframe_and_frame_elements(mode)
499 else {
500 return;
502 };
503
504 if url.matches_about_blank() && mode == ProcessingMode::FirstTime {
506 self.run_iframe_load_event_steps(cx);
508 return;
510 }
511
512 let document = self.owner_document();
515 let referrer_policy_token = self.ReferrerPolicy();
516
517 let referrer_policy = match ReferrerPolicy::from(&*referrer_policy_token.str()) {
521 ReferrerPolicy::EmptyString => document.get_referrer_policy(),
522 policy => policy,
523 };
524
525 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 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 fn create_nested_browsing_context(&self, cx: &mut JSContext) {
603 let document = self.owner_document();
605 let window = self.owner_window();
606 let pipeline_id = Some(window.pipeline_id());
607 *self.frozen_name.borrow_mut() = self
611 .upcast::<Element>()
612 .get_name()
613 .map(|name| name.to_string());
614 let mut load_data = LoadData::new(
616 LoadOrigin::Script(document.origin().snapshot()),
619 ServoUrl::parse("about:blank").unwrap(),
620 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 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 self.start_new_pipeline(
648 cx,
649 load_data,
650 PipelineType::InitialAboutBlank,
651 NavigationHistoryBehavior::Push,
652 ProcessingMode::FirstTime,
653 snapshot_self(self),
654 );
655 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 pub(crate) fn update_pipeline_id(
678 &self,
679 cx: &mut JSContext,
680 new_pipeline_id: PipelineId,
681 reason: UpdatePipelineIdReason,
682 ) -> bool {
683 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 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 pub(crate) fn note_pending_navigation(&self) {
775 self.pending_navigation.set(true);
776 }
777
778 pub(crate) fn load_finished(
782 &self,
783 cx: &mut JSContext,
784 loaded_pipeline: PipelineId,
785 aborted: bool,
786 ) {
787 if Some(loaded_pipeline) != self.pending_pipeline_id.get() {
790 return;
791 }
792
793 if aborted {
796 let blocker = &self.load_blocker;
797 LoadBlocker::terminate(cx, blocker);
798 return;
799 }
800
801 let should_fire_event = if self.is_initial_blank_document() {
830 !self.pending_navigation.get() &&
834 !self.upcast::<Element>().has_attribute(&local_name!("src"))
835 } else {
836 !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 pub(crate) fn run_iframe_load_event_steps(&self, cx: &mut JSContext) {
853 let child_document = self.GetContentDocument();
857
858 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 self.upcast::<EventTarget>().fire_event(cx, atom!("load"));
874
875 let blocker = &self.load_blocker;
876 LoadBlocker::terminate(cx, blocker);
877
878 if let Some(child_document) = self.GetContentDocument() {
880 child_document.set_iframe_load_in_progress(false);
881 }
882 }
883
884 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 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 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 fn destroy_child_navigable(&self, cx: &mut JSContext) {
916 let blocker = &self.load_blocker;
917 LoadBlocker::terminate(cx, blocker);
918
919 let Some(browsing_context_id) = self.browsing_context_id() else {
921 return;
923 };
924 let pipeline_id = self.pipeline_id.get();
927
928 self.destroy_nested_browsing_context();
936
937 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 }
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 make_url_getter!(Src, "src");
1004
1005 make_url_setter!(SetSrc, "src");
1007
1008 fn Srcdoc(&self) -> TrustedHTMLOrString {
1010 let element = self.upcast::<Element>();
1011 element.get_trusted_html_attribute(&local_name!("srcdoc"))
1012 }
1013
1014 fn SetSrcdoc(&self, cx: &mut JSContext, value: TrustedHTMLOrString) -> Fallible<()> {
1016 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 element.set_attribute(
1028 cx,
1029 &local_name!("srcdoc"),
1030 AttrValue::String(value.str().to_owned()),
1031 );
1032 Ok(())
1033 }
1034
1035 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 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 fn GetContentDocument(&self) -> Option<DomRoot<Document>> {
1074 let pipeline_id = self.pipeline_id.get()?;
1076
1077 let document = ScriptThread::find_document(pipeline_id)?;
1081 if !self
1083 .owner_document()
1084 .origin()
1085 .same_origin_domain(&document.origin())
1086 {
1087 return None;
1088 }
1089 Some(document)
1091 }
1092
1093 fn ReferrerPolicy(&self) -> DOMString {
1095 reflect_referrer_policy_attribute(self.upcast::<Element>())
1096 }
1097
1098 make_setter!(SetReferrerPolicy, "referrerpolicy");
1100
1101 make_bool_getter!(AllowFullscreen, "allowfullscreen");
1103 make_bool_setter!(SetAllowFullscreen, "allowfullscreen");
1105
1106 make_getter!(Width, "width");
1108 make_dimension_setter!(SetWidth, "width");
1110
1111 make_getter!(Height, "height");
1113 make_dimension_setter!(SetHeight, "height");
1115
1116 make_getter!(FrameBorder, "frameborder");
1118 make_setter!(SetFrameBorder, "frameborder");
1120
1121 make_atomic_setter!(SetName, "name");
1125
1126 make_getter!(Name, "name");
1130
1131 make_enumerated_getter!(
1134 Loading,
1135 "loading",
1136 "lazy" | "eager",
1137 missing => "eager",
1140 invalid => "eager"
1141 );
1142
1143 make_setter!(SetLoading, "loading");
1145
1146 make_url_getter!(LongDesc, "longdesc");
1148
1149 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 local_name!("sandbox") if self.browsing_context_id.get().is_some() => {
1179 self.parse_sandbox_attribute();
1180 },
1181 local_name!("srcdoc") => {
1182 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 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 if !mutation.is_removal() && &**attr.value() == "lazy" {
1221 return;
1222 }
1223
1224 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 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 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 self.parse_sandbox_attribute();
1275
1276 self.create_nested_browsing_context(cx);
1278
1279 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 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 self.destroy_child_navigable(cx);
1300
1301 self.owner_document().iframes().remove(cx.no_gc(), self);
1302 }
1303}
1304
1305pub(crate) struct IframeContext {
1308 url: ServoUrl,
1310}
1311
1312impl IframeContext {
1313 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}