2011-07-19 59 views
33

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

+0

如果你不想依靠入侵尝试我的答案在http://stackoverflow.com/questions/6086986/how-do-i-remove-an-iframe-from -within-that-that-been-dynamic-created – Rhys

回答

58

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

在IFrame:请

parent.closeIFrame(); 

在父:

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

@citizen,如果我没有控制权的父域。这可以在iframe中处理吗?像在iframe中一样,通过parent.getElementByID(“iFrameID”)。remove();引用iframe本身。 – Stan

+9

哦,它是跨域?如果不进入一个全新的痛苦世界,你将无法操纵dom。 –

+0

父对象是相当有效的..我认为这是如何与iframe关联其父母页面? – efirat

11
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" /> 
+1

这不会工作!几秒钟内完成。我推荐它! – Laci

+1

这个工作,但不跨域:( –

+0

年后,我知道,但我只想指出,你不必要地调用getElementById两次。'closeWin()'的第二行应该是'someIframe.parentNode。 removeChild(someIframe);'。 – Doin

2

使用此功能可以从母公司的iframe本身

frameElement.parentNode.removeChild(frameElement) 

它与同一产地内删除IFRAME只(不允许与十字架杜松子酒)

1

同类哈克,但它工作得很好十岁上下

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

获得幻想在你的框架页面的顶部,使重新加载不明显

所以基本上在第一时间框架加载它不隐藏自身,但它加载ITLL调用的onload函数和家长将有下一次的窗口VAR导致框架关闭

1

这个解决方案没有工作了因为我在跨域的方案创建像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的关闭命令:

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

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

希望它能帮助,

+0

你的偶数监听器函数的第二行(第2步)不必要地再次调用getElementById,它的参数和之前一样。 ' – Doin

+0

另外,我认为你的代码存在一个错误,如果事件监听器被注入并且在父窗口的上下文中运行,那么你不应该写'window.parent.document.getElementById(... )'而只是'document.getElementById(...)',因为它已经在*父窗口中。 – Doin