use crate::web_utils::HtmlEventListener;
use wasm_bindgen::JsCast;
use web_sys::HtmlIFrameElement;
pub fn reload(iframe: &HtmlIFrameElement) {
iframe
.content_window()
.unwrap()
.location()
.reload()
.unwrap();
}
pub async fn reload_async(iframe: &HtmlIFrameElement) {
reload(iframe);
wait_for_load(iframe).await;
}
pub async fn set_source(iframe: &HtmlIFrameElement, url: &str) {
iframe.set_src(url);
wait_for_load(iframe).await;
if iframe.content_document().is_none() {
panic!(
"iframe loaded src: {url}\nbut content_document is None (likely a CORS issue)"
);
}
}
pub async fn wait_for_load(iframe: &HtmlIFrameElement) {
let target = iframe.clone().unchecked_into::<web_sys::EventTarget>();
let mut loads =
HtmlEventListener::<web_sys::Event>::new_with_target("load", target);
let _ = loads.next_event().await;
}
#[cfg(test)]
#[cfg(target_arch = "wasm32")]
mod tests {
use super::*;
use crate::prelude::*;
use crate::web_utils::document_ext as doc;
#[ignore = "requires dom"]
#[test]
fn works() {
let _ = doc::document();
let _ = doc::head();
let _ = doc::body();
}
#[ignore = "requires dom"]
#[crate::test]
async fn works_async() {
doc::clear_body();
let iframe: HtmlIFrameElement = doc::document()
.create_element("iframe")
.unwrap()
.dyn_into()
.unwrap();
doc::append_child(&iframe);
let data_url = "data:text/html,<html><body>ok</body></html>";
set_source(&iframe, data_url).await;
iframe.content_document().is_some().xpect_true();
reload_async(&iframe).await;
iframe.content_document().is_some().xpect_true();
}
}