How to Remove DIV from Iframe?

Remove a DIV from within it's child IFRAME (cross-domain)

  • I'm working on a bookmarklet that loads Javascript from my server. The JS adds a div with an embedded iframe (so I can pass/load content from my own domain). I cannot figure out how to remove the DIV element, including the iframe, from within the iframe. I can't reference window.parent because it is cross domain. window.postMessage looks like it might be the right idea, but I haven't found sufficient documentation that helps me understand it. I would very much like to have the iframe's close button within the iframe. Assistance is appreciated. EDIT: In my attempt to use window.postMessage, I have tried creating an event listener with the bookmarklet (ergo, on any domain): var receiveMessage = function(event) { $("#iframecontainerdiv").remove(); console.log (event); alert (event.origin); } window.addEventListener("message", receiveMessage, false); And then within the iframe, I tried to trigger it: $("#abort").click( function(e) { e.preventDefault(); window.close(); window.postMessage("Hello, World!", "*"); }); I'm not sure if I'm going about this right...

  • Answer:

    I think you're posting the message to the wrong window. Maybe you should be using window.top.postMessage to post a message instructing the top window to remove the iframe. So: var receiveMessage = function(event) { if ("close-iframe" == event.data) { $("#iframecontainerdiv").remove(); } console.log (event); alert (event.origin); } window.addEventListener("message", receiveMessage, false); and: $("#abort").click(function(e) { e.preventDefault(); window.top.postMessage("close-iframe", "*"); }); You could optionally test the origin of the message so that only messages from your domain result in the iframe being removed.

Mike S. at Stack Overflow Visit the source

Was this solution helpful to you?

Related Q & A:

Just Added Q & A:

Find solution

For every problem there is a solution! Proved by Solucija.

  • Got an issue and looking for advice?

  • Ask Solucija to search every corner of the Web for help.

  • Get workable solutions and helpful tips in a moment.

Just ask Solucija about an issue you face and immediately get a list of ready solutions, answers and tips from other Internet users. We always provide the most suitable and complete answer to your question at the top, along with a few good alternatives below.