Javascript 如何在iframe自身中关闭iframe

Javascript 如何在iframe自身中关闭iframe,javascript,jquery,iframe,Javascript,Jquery,Iframe,如何使用javascript或jQuery关闭iframe本身中的iframe?我尝试了,但没有成功。无法“关闭”当前iFrame,但您可以告诉父级操作dom并使其不可见 在IFrame中: parent.closeIFrame(); 在父项中: function closeIFrame(){ $('#youriframeid').remove(); } 函数closeWin()//已测试代码 { var someIframe=window.parent.document.getE

如何使用javascript或jQuery关闭iframe本身中的iframe?我尝试了
,但没有成功。

无法“关闭”当前iFrame,但您可以告诉父级操作dom并使其不可见

在IFrame中:

parent.closeIFrame();
在父项中:

function closeIFrame(){
     $('#youriframeid').remove();
}
函数closeWin()//已测试代码
{
var someIframe=window.parent.document.getElementById('iframe_callback');
someIframe.parentNode.removeChild(someIframe));
}

使用此选项从iframe本身的父级中删除iframe

frameElement.parentNode.removeChild(frameElement)

它只适用于同一来源(不允许跨来源)

它有点老套,但效果很好

 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>
如果你想通过一个

if(isset($_GET['close'])){
  die;
}
在框架页面的顶部,使重新加载不可见


因此,基本上,第一次加载帧时,它不会隐藏自己,但下一次加载时,它会调用onload函数,父对象将有一个窗口变量,导致帧关闭

由于我正在跨域场景中创建一个书签,如Pinterest的Pin it

我在GitHub上找到了一个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'
                }]);
跟着模板走,你会没事的


如果我无法控制父域,希望它能有所帮助,

@citizen。这可以在iframe本身中处理吗?与在iframe中一样,通过parent.getElementByID(“iFrameID”).remove()引用iframe本身;哦,是跨域的?如果不进入一个全新的痛苦世界,您将无法操纵dom。父对象非常有效。。我想这就是iframe如何关联其父页面?@citizenconn如果iframe是跨域的,我们必须设置“x-frame-options”吗?值得一提的是,我能够用document.getElementById(“iframeID”).remove()关闭iframe;这是indead的作品!在几秒钟内实现了它。我推荐它!我知道,已经晚了很多年,但我只想指出,你不必要地给getElementById打了两次电话。
closeWin()
的第二行应该是
someIframe.parentNode.removeChild(someIframe)
。这很神奇,但实际上,您可以删除第二个get元素。如果您不想依赖id,请在偶数侦听器函数(步骤2)的第二行尝试我的答案,第二次不必要地使用与前面相同的参数调用getElementById。这一行应该是:
someIframe.parentNode.removeChild(someIframe)另外,我认为您的代码中有一个错误。如果事件侦听器被注入父窗口并在其上下文中运行,那么您不应该编写
window.parent.document.getElementById(…)
,而应该只编写
document.getElementById(…)
,因为它已经在父窗口中。
    window.addEventListener('message', function(e) {
       var someIframe = window.parent.document.getElementById('iframeid');
       someIframe.parentNode.removeChild(window.parent.document.getElementById('iframeid'));
    });
   $(this).trigger('post-message', [{
                    event: 'unload-bookmarklet'
                }]);