在Iframe中加载html并访问DOM [英] Load html in Iframe and access the DOM
问题描述
我想使用JavaScript将html文件加载到 iframe
中,然后访问DOM并从我的html文件中获取id的元素,这是我的代码:
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>
这是我的htmleditor.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>
所以我要做的是加载我的 editor.html
进入 iframe
,然后从iframe访问并从我的 image.src
获取 editor.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:
无法读取空的src
cannot read src of null
推荐答案
如果iframe页面中包含jquery库,您可以尝试以下方法来查找iframe的父级;
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();
这篇关于在Iframe中加载html并访问DOM的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!