如何关闭 iframe 本身内的 iframe

问题描述 投票:0回答:6

如何使用 javascript 或 jQuery 关闭 iframe 本身内的 iframe?我已经尝试过

<a href="javascript:self.close()">
但没有成功。

javascript jquery iframe
6个回答
90
投票

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

在 IFrame 中:

parent.closeIFrame();

家长:

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

17
投票
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" /> 

9
投票

使用它可以从 iframe 本身的父级中删除 iframe

frameElement.parentNode.removeChild(frameElement)

仅适用于同源(不允许跨源)


6
投票

这个解决方案对我来说都不起作用,因为我处于跨域场景中创建一个像 Pinterest 的 Pin It 这样的书签。


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 函数,并且父级将有一个窗口变量导致框架关闭


0
投票

不幸的是,如果父/子应用程序的域不同,上述解决方案将不起作用。相反,您可以使用 window.postMessage API。

这是 React 中的一个简单示例。

在主应用程序中

const [open, setOpen] = React.useState(false);
useEffect(() => {
  window.addEventListener("message", (event) => { 
    if (event.data === "closeWindow") {
      setOpen(false);
    }
  });
}, []);

在 iframe 应用程序中

<Button
  onClick={() => {
    window.parent.postMessage("closeWindow", "*");
  }}
>
  close
</Button>

在此示例中,我演示了子对父通信,但 API 支持双向。

© www.soinside.com 2019 - 2024. All rights reserved.