Appending HTML to parent from inside iFrame without jQuery

不羁的心 提交于 2021-01-05 06:42:18

问题


I'm developing in an application where new code is introduced via iframes only. I'm trying to create a function (running inside an iFrame) that will append some html after the iFrame in which it is running. I'd rather not introduce jQuery to resolve this issue. Here is a sample

    function AppendDivAfteriFrame() {
        var iFrame = window.parent.document.getElementById(window.frameElement.id)
        var newDivInParent = window.parent.document.createElement('div');
        newDivInParent.setAttribute("Id", "MyDiv");
        newDivInParent.innerHTML = 'Hello World!  I am outside the iFrame';
        iFrame.appendChild(newDivInParent);
    }

I don't receive any exceptions, but I never see any results either.

Update with full code

Call this page InnerPage.html

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <script type="text/javascript">
        function AppendDivAfteriFrame() {
            var iFrame = window.parent.document.getElementById(window.frameElement.id)
            var newDivInParent = window.parent.document.createElement('div');
            newDivInParent.setAttribute("Id", "MyDiv");
            iFrame.appendChild(newDivInParent);
            parent.document.getElementById('MyDiv').innerHTML = 'Hello World! I am outside the iFrame';
        }
    </script>
</head>
<body>
    <button onclick="AppendDivAfteriFrame()">Append HTML</button>    
</body>
</html>

Call this page OuterPage.html

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
</head>
<body>
    <iframe src="InnerPage.html" id="MyiFrame"></iframe>
</body>    
</html>

回答1:


This works:

function AppendDivAfteriFrame() {
     var iFrame = window.parent.document.getElementById(window.frameElement.id)
     var newDivInParent = window.parent.document.createElement('div');
     newDivInParent.setAttribute("Id", "MyDiv");
     iFrame.parentNode.appendChild(newDivInParent);  //Edited here
     parent.document.getElementById('MyDiv').innerHTML = 'Hello World! I am outside the iFrame';           
}


来源:https://stackoverflow.com/questions/19556432/appending-html-to-parent-from-inside-iframe-without-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!