admin管理员组

文章数量:1279125

I want to close an iframe by clicking a button inside that iframe and e back out to the parent page.

I have searched but could not get appropriate code.

Can anybody help me?

I want to close an iframe by clicking a button inside that iframe and e back out to the parent page.

I have searched but could not get appropriate code.

Can anybody help me?

Share Improve this question edited Nov 3, 2011 at 6:59 evan 12.6k7 gold badges40 silver badges52 bronze badges asked Nov 3, 2011 at 6:54 SANJOY SAHASANJOY SAHA 311 gold badge1 silver badge2 bronze badges 3
  • you can't close an iframe! but you need to navigate to another page.. window.top.location.href = "newlocation.htm" – Ayyash Commented Nov 3, 2011 at 7:04
  • 2 You really can't put the button outside? – Nicolas Commented Nov 3, 2011 at 7:06
  • second what @graphox said. it'd be a simple $("#iframe_id").remove() jQuery call. – Patrick Moore Commented Nov 3, 2011 at 7:07
Add a ment  | 

7 Answers 7

Reset to default 3

Try this

function closeIframe() [
   var iframe = document.getElementById('someid');
   iframe.parentNode.removeChild(iframe);
}

You need to assign an id to your iframe, like <iframe id="someid"...

Then you need a function to remove the iframe:

<a href="javascript: window.parent.document.getElementById('someid').parentNode.removeChild(window.parent.document.getElementById('someid'))">Close</a>

This was covered here: Close iframe cross domain using a much more flexible method which is cross-domain functional.

<a href="window.parent.document.getElementById('someid').parentNode.removeChild(window.parent.document.getElementById('someid'))">Close</a>

I have something like this in button onclick function:

parent.location.reload();  

I guess this may help you:

var theFrame=parent.getElementById("iframeId");  
theFrame.parentNode.removeChild(theFrame);

iframe are a tricky one but i've had my share of fun with them. when trying to access an iframe from the "top" document, you would use:


top.iFrameToClose = top.document.getElementById("myiFrame");
top.iFrameToClose.offsetParent.removeChild(top.iFrameToClose);

i hope that helped...

Using the PostMessage API, an iframe can be closed from an onclick event inside the frame.

Parent

<script>
    window.addEventListener('message', function(event) {
        console.log("Message received from the child: " + event.data); //Message received from child
    });
</script>

Child iframe code

<button id="sendMessage">Send Message to Parent</button>
<script>
    var button = document.querySelector("#sendMessage");
    button.addEventListener("click", function () {
        // Send `message` to the parent using the postMessage method on the window.parent reference.
        window.parent.postMessage('message', "*");
    });
</script>

本文标签: phpHow do I close an iframe from an onclick event inside the iframeStack Overflow