简体   繁体   中英

Load html in Iframe and access the DOM

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

如果iframe页面中包含jquery库,则可以尝试以下方法找到iframe的父项;

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM