JSFiddle - React, Tailwind, and code Playground
HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Iframe Focus Test</title>
</head>
<body>
<script>
window.onload = async function () {
// Create two iframes and add them to the document.
const iframe1 = document.createElement("iframe");
const iframe2 = document.createElement("iframe");
document.body.appendChild(iframe1);
document.body.appendChild(iframe2);
// Helper function to load an iframe with about:blank.
function loadIframe(iframe) {
return new Promise(resolve => {
iframe.onload = resolve;
iframe.src = "about:blank";
});
}
// Load both iframes.
await Promise.all([loadIframe(iframe1), loadIframe(iframe2)]);
// Focus the first iframe.
iframe1.focus();
// A slight delay can help ensure the focus event propagates.
await new Promise(resolve => setTimeout(resolve, 0));
console.assert(
iframe1.contentDocument.hasFocus(),
"iframe1 is not focused after calling focus()"
);
// Focus the second iframe.
iframe2.focus();
await new Promise(resolve => setTimeout(resolve, 0));
console.assert(
iframe2.contentDocument.hasFocus(),
"iframe2 is not focused after calling focus()"
);
// Swap focus back to the first iframe.
iframe1.focus();
await new Promise(resolve => setTimeout(resolve, 0));
console.assert(
iframe1.contentDocument.hasFocus(),
"iframe1 is not focused after swapping focus back"
);
console.log("Iframe focus test completed.");
};
</script>
</body>
</html>