Load html in Iframe and access the DOM

2019-08-15 22:13发布

问题:

I want to load a html file into an iframe using JavaScript, then access the DOM and get an element by id from my html file, this is my code :

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

And this is a part of my 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>

So What I'm trying to do is to load my editor.html into an iframe, then access from the iframe and get the image.src from my editor.html. I try but i'm getting error:

cannot read src of null

回答1:

If you have jquery library included in iframe page, You can try the following to find the parent of the iframe;

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