可以解析在iframe中显示的html网页中的标签吗?我尝试按如下方式编译代码,但它不起作用。
<!DOCTYPE html>
<html>
<body>
<iframe id="Frame" src="Url"></iframe>
<button onclick="myFunction()">Parse it</button>
<p id="demo"></p>
<script>
function myFunction() {
var x = document.getElementById("Frame").src.getElementByTagName("title");
document.getElementById("demo").innerHTML = x;
}
</script>
</body>
</html>
发布于 2016-03-17 06:15:50
您可以执行类似以下的操作。只需记住将iframe的src更改为您实际加载的页面的url:
<!DOCTYPE html>
<html>
<body>
<iframe id="Frame" src="sample.html"></iframe>
<button onclick="myFunction()">Parse it</button>
<p id="demo"></p>
<script>
function myFunction() {
var x;
//get the iframe object
var iframe = document.getElementById('Frame');
//cross browser solution to get the iframe document
//of the iframe
var iframeDocument = iframe.contentDocument || iframe.contentWindow.document;
//if the document is not undefined
if (iframeDocument) {
//do something with the frames dom
//get the content of the title tag from the iframe
x = iframeDocument.getElementsByTagName("title")[0].innerHTML;
}
document.getElementById("demo").innerHTML = x;
}
</script>
</body>
</html>
注意:此解决方案在不允许在iframes中跨域加载的网站上不起作用。例如,如果您要将url http://www.google.com
添加到iframe的src中,它将在开发人员控制台中显示以下错误。
Load denied by X-Frame-Options: https://www.google.com/?gws_rd=ssl does not permit cross-origin framing.
由于同样的原因,这是您可能收到的另一个错误。我在自己的网站(bytewarestudios.com)上试用时收到了这个错误。
Error: Permission denied to access property "document"
https://stackoverflow.com/questions/36047483
复制相似问题