【问题标题】:Load html in Iframe and access the DOM在 iframe 中加载 html 并访问 DOM
【发布时间】:2015-12-27 19:40:31
【问题描述】:

我想使用 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 访问并从我的editor.html 获取image.src。 我尝试但我收到错误:

无法读取 null 的 src

【问题讨论】:

  • 尝试获取 iFrame 的 innerHTML,然后将其加载到基本虚拟 dom 中,然后从中提取 img.src
  • 对我来说很好用:randume.org/testscrpts/test2.php。检查是否正在创建图像?也可能与 &lt;head&gt; 中的 iframe 有关。试着把它移到身体上。
  • 你找到解决办法了吗?

标签: javascript jquery html iframe


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-03-21
    • 2012-12-29
    • 1970-01-01
    • 1970-01-01
    • 2012-06-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多