【发布时间】:2011-10-08 22:56:16
【问题描述】:
如何使用 javascript 或 jQuery 关闭 iframe 本身内的 iframe?我试过<a href="javascript:self.close()">,但没用。
【问题讨论】:
-
如果您不想依赖 id,请在 stackoverflow.com/questions/6086986/… 尝试我的回答
标签: javascript jquery iframe
如何使用 javascript 或 jQuery 关闭 iframe 本身内的 iframe?我试过<a href="javascript:self.close()">,但没用。
【问题讨论】:
标签: javascript jquery iframe
“关闭”当前 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" />
【讨论】:
closeWin() 的第二行应该是 someIframe.parentNode.removeChild(someIframe);。
使用它从 iframe 本身的父级中删除 iframe
frameElement.parentNode.removeChild(frameElement)
它只适用于同源(不允许跨源)
【讨论】:
这个解决方案都不适合我,因为我在一个跨域场景中创建一个像 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 上的模板,你会没事的!
希望对你有帮助,
【讨论】:
someIframe.parentNode.removeChild(someIframe);
window.parent.document.getElementById(...),而应该只写document.getElementById(...),因为它已经在父窗口中。
它有点老套,但效果很好
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 函数,并且父级将有一个导致框架关闭的窗口变量
【讨论】: