微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何使用javascript删除自身内的iframe

我知道有几个类似的问题,但由于无法解决问题,我不得不再次使用附加代码提出问题.
我在JSF项目中有两个.xhtml文件.一个是mainPage.xhtml,它有一个生成动态HTML代码的按钮,用于创建iframe(iFramePage.xhtml)并在浏览器上显示;

nes work properly when I call inside this page,*/
        /*..however it does not work by calling from iFramePage.xhtml */                

        //document.getElementById("iFrameContainer").removeChild("iframe0");
        $('iframe0').remove();
        }
    

另一页是iFramePage.xhtml,它有一些html和javascript代码;

 nes works properly,however third line does not work!*/
            //window.top.location.href = "HIDDEN"; 
            //parent.document.location.href = "HIDDEN";
            parent.removeElement();

        }
    

我可以通过单击“cntrBtn1”按钮生成iframe,然后通过单击mainPage.xhtml中的“cntrBtn2”进行删除.但是,我需要删除内部的iframe(iFramePage.xhtml).当我点击iFramePage.xhtml中的“exitBtn”时,iframe不会消失.没有关于跨域的内容,因为mainPage.xhtml和iFramePage.xhtml在同一个JSF项目中,即使在同一目录中也是如此.我可以重定向页面(在iFramePage.xhtml中查看closeSelf()中的两行),但我无法使用父元素删除iframe,为什么!请帮我 :)

最佳答案
使用window.postMessage在父级和iframe之间进行通信.

将iframe页面中的closeSelf()函数替换为以下内容

function closeSelf() {
   parent.window.postMessage("removetheiframe","*");
}

并在父页面添加以下代码,以便在iframe发送消息时进行监听:

function receiveMessage(event){
   if (event.data=="removetheiframe"){
      var element = document.getElementById('iframe-element');
      element.parentNode.removeChild(element);
   }
}
window.addEventListener("message",receiveMessage,false);

您还可以在event.origin之前检查postMessage的来源,以确保请求删除iframe的iframe.

原文地址:https://www.jb51.cc/html/426842.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐