在Iframe中加载html并访问DOM

时间:2015-12-27 19:40:31

标签: javascript jquery html iframe

我想使用JavaScript将html文件加载到iframe,然后访问DOM并从我的html文件中获取id的元素,这是我的代码:

<html>
    <head>
       <iframe id="myframe" src="editor1.html" onload="onMyFrameLoad()"></iframe>
    </head>
    <body >
    <script>
        function onMyFrameLoad() {
              alert('myframe is loaded');
               var if1 = document.getElementById("myframe");
               var fc = (if1.contentWindow || if1.contentDocument);
               var img1 = fc.document.getElementById("GraphImage");
               console.log(img1.src);
       };
    </script>
    </body>
</html>

这是我的html“editor.html”的一部分:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Diagram</title>    
<script>
    // i have here other functions to create an editor 
    function generatePNGFromBLOB(oViewer) {
        a=1000;
        var oImageOptions = {
            includeDecoratorLayers: false,
            replaceImageURL: true
        };

        var d = new Date();
        var h = d.getHours();
        var m = d.getMinutes();
        var s = d.getSeconds();

        var sFileName = "diagram" + h.toString() + m.toString() + s.toString() + ".png";
        var sResultBlob = oViewer.generateImageBlob(function(sBlob) {
            b = 64;
            var reader = new window.FileReader();
            reader.readAsDataURL(sBlob);
            reader.onloadend = function() {
                base64data = reader.result;
                var image = document.createElement('img');
                image.setAttribute("id", "GraphImage");
                //code image in base 64
                image.src = base64data;
                document.body.appendChild(image);
            }

        }, "image/png", oImageOptions);
        return sResultBlob;
    }

    $(document).ready(function() {
        var sBlob = JSON.stringify({
            "contents": {   //string}
            }
        });

        var sResultBlob = generatePNGFromBLOB(oEditor.viewer);

    });
</script>


</head>

<body>
    <div id="diagramContainer"></div>
</body>
</html>

所以我要做的是将editor.html加载到iframe,然后从iframe访问并从image.src获取editor.html。 我尝试但是我得到了错误:

  

无法读取null的src

1 个答案:

答案 0 :(得分:0)

如果iframe页面中包含jquery库,您可以尝试以下方法来查找iframe的父级;

$('#domElem', window.parent.document).html();