如何在iframe中关闭iframe

时间:2011-07-19 22:35:21

标签: javascript jquery iframe

如何使用javascript或jQuery在iframe中关闭iframe?我已经尝试了<a href="javascript:self.close()">,但它没有用。

5 个答案:

答案 0 :(得分:69)

“关闭”当前的iFrame是不可能的,但你可以告诉父母操纵dom并让它不可见。

在IFrame:

parent.closeIFrame();

在父母:

function closeIFrame(){
     $('#youriframeid').remove();
}

答案 1 :(得分:13)

function closeWin()   // Tested Code
{
var someIframe = window.parent.document.getElementById('iframe_callback');
someIframe.parentNode.removeChild(window.parent.document.getElementById('iframe_callback'));
}


<input class = question name="Close" type ="button" value = "Close" onClick = "closeWin()"     tabindex="10" /> 

答案 2 :(得分:4)

使用此功能从iframe本身的父级中移除iframe

frameElement.parentNode.removeChild(frameElement)

它仅适用于相同的原点(不允许使用交叉原点)

答案 3 :(得分:2)

这个解决方案都不适用于我,因为我在跨域方案中创建像Pinterest的Pin It这样的书签。

我在GitHub https://gist.github.com/kn0ll/1020251上找到了一个书签模板,解决了关闭从其中发送命令的Iframe的问题。

由于我无法访问IFrame中父窗口中的任何元素,因此只能使用window.postMessage

在两个窗口之间发布事件。

所有这些步骤都在GitHub链接上:

1-您必须在父页面上注入一个JS文件。

2-在父文件中注入的此文件中,添加一个窗口事件列表器

    window.addEventListener('message', function(e) {
       var someIframe = window.parent.document.getElementById('iframeid');
       someIframe.parentNode.removeChild(window.parent.document.getElementById('iframeid'));
    });

此侦听器将处理您希望的关闭和任何其他事件

3-在Iframe页面中,您可以通过postMessage发送close命令:

   $(this).trigger('post-message', [{
                    event: 'unload-bookmarklet'
                }]);

按照https://gist.github.com/kn0ll/1020251上的模板进行操作,您就可以了!

希望它有所帮助,

答案 4 :(得分:1)

它有点hacky但是效果很好

 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>

然后在框架内

$('#close_modal_main').click(function(){
        window.location = 'iframe_index.php?close=1';
});

如果你想通过

获得幻想
if(isset($_GET['close'])){
  die;
}

位于框架页面的顶部,以使重新加载不明显

所以基本上第一次加载它时它不会隐藏自己,但是下次加载它时会调用onload函数,而父类将有一个窗口var导致框架关闭

相关问题