如何在iframe内部关闭iframe

How to close an iframe within iframe itself

本文关键字:iframe 内部      更新时间:2023-09-26

我如何使用javascript或jQuery关闭iframe内的iframe本身?我试过<a href="javascript:self.close()">,但它没有工作。

"关闭"当前iFrame是不可能的,但你可以告诉父类操作dom并使其不可见。

在IFrame:

parent.closeIFrame();
在父母

:

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" /> 

将iframe从iframe中移除

frameElement.parentNode.removeChild(frameElement)

只适用于相同原点(不允许交叉原点)

这些解决方案都不适合我,因为我是在一个跨域的场景中创建一个像Pinterest的Pin It这样的书签。

我在GitHub https://gist.github.com/kn0ll/1020251上找到了一个bookmarklet模板,解决了关闭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上的模板,你会没事的!

希望有帮助,

这有点粗糙,但效果很好

 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';
});

if(isset($_GET['close'])){
  die;
}

在你的框架页面的顶部,使重载不明显

所以基本上在框架第一次加载时它不会隐藏自己但是下次加载时它会调用onload函数父元素会有一个window变量导致框架关闭