Your Search Bar For Shrewd Tips

How To Close Iframe In Javascript


Knowing how to close an iframe in JavaScript depends on what “close” means and where your code runs. An iframe is an element in its parent page, not a separate browser tab, so the most reliable approach is usually for the parent page to hide or remove the iframe. If the iframe needs to request its own closure, the solution depends on whether it shares the parent’s origin. This guide covers the common methods, including same-origin JavaScript, cross-origin messaging, modal dialogs, and security considerations.

The key distinction is control: JavaScript running on the parent page can manage the iframe element directly, while JavaScript running inside the iframe may be restricted from accessing the parent document. Choose the method that matches your page structure rather than trying to close the iframe with window.close().

Can JavaScript Close an Iframe?

An iframe does not behave like a browser tab or popup window. It is an HTML element embedded in another document. As a result, calling window.close() from inside an iframe generally will not remove or close that iframe. Browsers restrict script-based window closing, and an iframe is not a separately opened tab in the usual sense.

To close an iframe, you typically either remove its <iframe> element from the parent page or hide it with CSS. The parent page can do this directly. Code inside the iframe can also do it when the parent and iframe are same-origin, or it can ask the parent to do it using postMessage() when they are cross-origin.

Remove an Iframe from the Parent Page

If your JavaScript runs in the parent document, removing the iframe is the simplest way to close it. Give the iframe an ID, then select it and call remove(). Once removed, the iframe and its embedded content are no longer part of the page.

<iframe id="helpFrame" src="/help.html" title="Help"></iframe>

<button id="closeHelp" type="button">Close help</button>

<script>
  const iframe = document.getElementById("helpFrame");

  document.getElementById("closeHelp").addEventListener("click", () => {
    iframe.remove();
  });
</script>

This method is useful for embedded forms, video players, chat widgets, and modal content that should be fully dismissed. If the iframe is created dynamically, you can still remove it by keeping a reference to the element or selecting it by ID when the user clicks a close button.

For code that may run after the iframe has already been removed, check that the element exists before calling remove():

const iframe = document.getElementById("helpFrame");

if (iframe) {
  iframe.remove();
}

Removing the iframe is different from simply stopping its display. When removed, the element is no longer available in the document. If you need to show it again later, you will need to create a new iframe or preserve and reinsert the existing element.

Hide an Iframe Instead of Removing It

If the user should be able to reopen the same iframe without rebuilding it, hide it instead. The parent page can change its hidden property, set display: none, or toggle a CSS class.

const iframe = document.getElementById("helpFrame");

document.getElementById("closeHelp").addEventListener("click", () => {
  iframe.hidden = true;
});

To show it again, set hidden back to false. A CSS class is another flexible option when you want to control transitions or other visual states:

.is-hidden {
  display: none;
}

const iframe = document.getElementById("helpFrame");

function closeFrame() {
  iframe.classList.add("is-hidden");
}

function openFrame() {
  iframe.classList.remove("is-hidden");
}

Hiding keeps the iframe in the document, so its content may remain loaded and its JavaScript may continue running. For an iframe that plays audio or video, handles sensitive information, or uses significant resources, removing it may be more appropriate. You can also pause or reset the embedded content before hiding it, depending on what the iframe contains.

Close an Iframe from Same-Origin JavaScript

Two pages are generally considered same-origin when they use the same scheme, host, and port. For example, pages served from the same HTTPS domain and port can usually access each other’s documents, subject to browser security rules. If code inside the iframe is same-origin with its parent, it can access the parent document and remove the iframe element.

One option is to find the iframe by ID in the parent document:

// Run this code inside a same-origin iframe.
const frame = window.parent.document.getElementById("helpFrame");

if (frame) {
  frame.remove();
}

You can also use window.frameElement from inside the iframe. It refers to the iframe element that contains the current document when the browser allows access:

// Run this code inside a same-origin iframe.
if (window.frameElement) {
  window.frameElement.remove();
}

This can be convenient because it does not require the iframe to have a particular ID. However, direct access from the child document to the parent is not suitable for cross-origin pages. If the parent and iframe have different origins, the browser will block access to parent.document for security reasons.

Ask a Cross-Origin Parent to Close the Iframe

When the iframe and parent are on different origins, use window.postMessage() to send a close request. The iframe sends a message to its parent, and the parent listens for that message. The parent—not the iframe—then removes or hides the iframe element.

In the iframe, send a message to the parent using the parent page’s exact origin as the target origin:

// Run this code inside the iframe.
window.parent.postMessage(
  { type: "CLOSE_IFRAME" },
  "https://www.example.com"
);

Replace https://www.example.com with the origin of the page that embeds the iframe. Do not use "*" as the target origin when you know the intended parent origin. A specific target origin helps prevent the message from being delivered to an unexpected page.

On the parent page, verify both the sender’s origin and the iframe window before acting on the message:

const iframe = document.getElementById("helpFrame");

window.addEventListener("message", (event) => {
  if (event.origin !== "https://widget.example.net") {
    return;
  }

  if (event.source !== iframe.contentWindow) {
    return;
  }

  if (event.data?.type === "CLOSE_IFRAME") {
    iframe.remove();
  }
});

Change https://widget.example.net to the iframe’s actual origin. Checking event.origin confirms which origin sent the message, while checking event.source confirms that it came from the expected iframe. These checks matter because other windows or frames may also send messages to the parent page.

For extra reliability, register the message listener after the iframe reference is available, and account for cases where the iframe may already have been removed. If the parent can create several iframe instances, associate each message with the correct frame rather than relying on a single global ID.

Close an Iframe Used in a Modal

Many websites display an iframe inside a modal or lightbox. In this setup, “close the iframe” may mean closing the entire modal, not just removing the embedded element. The parent page should handle the close button, update the modal’s visibility, and optionally remove the iframe to stop its content.

<div id="helpModal" role="dialog" aria-modal="true"
     aria-labelledby="helpTitle" hidden>
  <h2 id="helpTitle">Help</h2>
  <button id="closeModal" type="button">Close</button>
  <iframe id="helpFrame" src="/help.html" title="Help content"></iframe>
</div>

<script>
  const modal = document.getElementById("helpModal");
  const iframe = document.getElementById("helpFrame");

  document.getElementById("closeModal").addEventListener("click", () => {
    modal.hidden = true;
    iframe.src = "about:blank";
  });
</script>

Setting the iframe’s source to about:blank can stop its current page from running while retaining the iframe element for later reuse. Depending on your needs, you can instead remove the iframe from the modal or remove the modal itself. If you hide a modal, also consider returning keyboard focus to the button that opened it and ensuring that keyboard users can reach the close control.

Why window.close() Usually Does Not Work

A common attempt is to call window.close() from the iframe. This is intended for closing script-opened browsing contexts in limited circumstances, not for removing an iframe element from a page. Browsers may ignore the call, and even when it applies to a window context, it is not the right way to close embedded content.

Use the parent’s DOM to remove or hide the iframe instead. If the iframe is cross-origin, send a message and let the parent decide whether to close it. This pattern is more predictable and makes the ownership of the iframe clear.

Security and Browser Considerations

Cross-origin restrictions protect the parent page and embedded page from accessing each other’s private data. Do not try to bypass those protections. Use a deliberate messaging interface, validate incoming messages, and avoid trusting message data merely because it came from an iframe.

  • Use exact origins: Set a specific target origin in postMessage() and compare event.origin against the expected origin.
  • Check the sender: When appropriate, compare event.source with the intended iframe’s contentWindow.
  • Validate message data: Accept only the message types your application expects, such as CLOSE_IFRAME.
  • Consider sandbox settings: The iframe’s sandbox attribute can restrict scripts and other behavior. Configure permissions only when they are needed.
  • Handle missing elements: Check that the iframe still exists before removing it, especially in applications where several controls can change the page.

A sandboxed iframe without allow-same-origin may have an opaque origin, which can make origin-based message checks more complicated. Avoid treating an origin value of "null" as proof that a message is safe. Where possible, design the parent to control iframe dismissal through its own interface, or use a carefully scoped messaging setup that also verifies the message source and expected data.

Choosing the Right Method

For most implementations, the parent page should own the iframe’s lifecycle. Use remove() when the embedded content should be discarded, and use CSS or the hidden property when it should remain available for reopening. Use same-origin access only when both documents are under your control and share an origin. For a cross-origin iframe that needs to request closure, use postMessage() with strict validation.

In short, do not rely on window.close() to close an iframe. Identify the parent element, decide whether it should be removed or hidden, and make sure any request from an embedded page is safely handled by the parent.

Conclusion

Closing an iframe in JavaScript is straightforward once you distinguish the iframe element from a browser window. Parent-page code can remove the iframe with element.remove() or hide it for later reuse. Same-origin iframe code can access its parent when permitted, while cross-origin iframe code should request closure through postMessage(). Validate messages, respect browser security boundaries, and choose between hiding and removing based on whether the embedded content should keep running. With the right approach, you can close an iframe reliably and safely across common JavaScript use cases.


Disclaimer: Articles are written by Humans, AI or Both. Verify Important information.

Shrewdnia

Shrewdnia

Shrewdnia is a destination for curious minds seeking clarity, knowledge, and informed perspectives. Through insightful articles and practical guides our passionate team explores a wide range of topics designed to help readers understand the world around them, make smarter decisions, and stay informed in an ever-changing landscape.


💡 Every question sparks discovery, and every perspective enriches the conversation. Share your thoughts and insights in the comments 👇

Back to blog

Leave a comment

JOIN THE SHREWDNIA COMMUNITY FORUM

What do you think?

Have an opinion, experience, or question about this topic? Join the Shrewdnia Forum and share your thoughts with other readers.

Join the Forum →