如何在iframe中关闭iframe

Sta*_*tan 48 javascript iframe jquery

如何在iframe中使用javascript或jQuery关闭iframe?我试过<a href="javascript:self.close()">但是没用.

cit*_*onn 71

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

在IFrame中:

parent.closeIFrame();
Run Code Online (Sandbox Code Playgroud)

在父母:

function closeIFrame(){
     $('#youriframeid').remove();
}
Run Code Online (Sandbox Code Playgroud)

  • 哦,这是跨领域?如果不进入一个全新的痛苦世界,你将无法操纵dom. (14认同)

小智 15

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" /> 
Run Code Online (Sandbox Code Playgroud)

  • 这有效,但不跨域:( (3认同)
  • 我知道,已经很晚了几年,但我只想指出你不必要地两次调用getElementById.`closeWin()`的第二行应该是`someIframe.parentNode.removeChild(someIframe);`. (2认同)

小智 6

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

frameElement.parentNode.removeChild(frameElement)
Run Code Online (Sandbox Code Playgroud)

它仅适用于相同的起源(不允许交叉起源)


Raf*_*újo 5

由于我在跨域场景中创建了像 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'));
    });
Run Code Online (Sandbox Code Playgroud)

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

3- 在 Iframe 页面内,您通过 postMessage 发送关闭命令:

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

按照https://gist.github.com/kn0ll/1020251上的模板操作,你会没事的!

希望能帮助到你,