How to close an iframe within iframe itself
How do I use开发者_Go百科 javascript or jQuery to close an iframe within iframe itself? I've tried <a href="javascript:self.close()">
but it didn't work.
"Closing" the current iFrame is not possible but you can tell the parent to manipulate the dom and make it invisible.
In IFrame:
parent.closeIFrame();
In parent:
function closeIFrame(){
$('#youriframeid').remove();
}
function closeWin() // Tested Code
{
var someIframe = window.parent.document.getElementById('iframe_callback');
someIframe.parentNode.removeChild(someIframe));
}
<input class="question" name="Close" type="button" value="Close" onClick="closeWin()" tabindex="10" />
Use this to remove iframe from parent within iframe itself
frameElement.parentNode.removeChild(frameElement)
It works with same origin only(not allowed with cross origin)
None of this solution worked for me since I'm in a cross-domain scenario creating a bookmarklet like Pinterest's Pin It.
I've found a bookmarklet template on GitHub https://gist.github.com/kn0ll/1020251 that solved the problem of closing the Iframe sending the command from within it.
Since I can't access any element from parent window within the IFrame, this communication can only be made posting events between the two windows using window.postMessage
All these steps are on the GitHub link:
1- You have to inject a JS file on the parent page.
2- In this file injected on the parent, add a window event listner
window.addEventListener('message', function(e) {
var someIframe = window.parent.document.getElementById('iframeid');
someIframe.parentNode.removeChild(window.parent.document.getElementById('iframeid'));
});
This listener will handle the close and any other event you wish
3- Inside the Iframe page you send the close command via postMessage:
$(this).trigger('post-message', [{
event: 'unload-bookmarklet'
}]);
Follow the template on https://gist.github.com/kn0ll/1020251 and you'll be fine!
Hope it helps,
its kind of hacky but it works well-ish
function close_frame(){
if(!window.should_close){
window.should_close=1;
}else if(window.should_close==1){
location.reload();
//or iframe hide or whatever
}
}
<iframe src="iframe_index.php" onload="close_frame()"></iframe>
then inside the frame
$('#close_modal_main').click(function(){
window.location = 'iframe_index.php?close=1';
});
and if you want to get fancy through a
if(isset($_GET['close'])){
die;
}
at the top of your frame page to make that reload unnoticeable
so basically the first time the frame loads it doesnt hide itself but the next time it loads itll call the onload function and the parent will have a the window var causing the frame to close
精彩评论