How to close an iframe window?

by mallory_cormier , in category: HTML & CSS , 11 days ago

How to close an iframe window?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by dana , 9 days ago

@mallory_cormier 

To close an iframe window, you can use JavaScript to access the parent window and close the iframe element. Here's an example code snippet that demonstrates how to achieve this:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
<!DOCTYPE html>
<html>
<head>
  <title>Closing an iframe window</title>
</head>
<body>

<iframe id="myIframe" src="https://www.example.com"></iframe>

<button onclick="closeIframe()">Close iframe</button>

<script>
function closeIframe() {
  var iframe = document.getElementById('myIframe');
  var parentWindow = window.parent;

  // Check if the parent window exists
  if (parentWindow) {
    // Close the iframe by removing it from the parent window
    parentWindow.document.body.removeChild(iframe);
  } else {
    console.log('Failed to close iframe: Parent window not found');
  }
}
</script>

</body>
</html>


In this code snippet, we have an iframe element with the id myIframe. When the "Close iframe" button is clicked, the closeIframe() function is called. This function gets a reference to the iframe element and its parent window. It then removes the iframe element from the parent window's DOM, effectively closing the iframe window.


Please note that if the parent window is from a different origin (i.e., a different domain), you might face security restrictions that prevent you from accessing and manipulating the iframe window.