使用JavaScript下载extern网页

时间:2016-06-30 15:25:21

标签: javascript html iframe

我想通过JavaScript下载html代码。此HTML代码是一个外部网页,将以iframe格式显示。是否可以获取HTML-Code在此iframe中的显示方式。

所以这是我的尝试:

<body>
    <iframe id="iframe_htmlcode1" name="iframe_htmlcode" src="http://www.w3schools.com"></iframe>
<textarea id="TextArea1" name="S1"></textarea>

    <script>
        function getAndSetContent() {

            var x = document.getElementById("iframe_htmlcode1");
            var y = (x.contentWindow || x.contentDocument);

            document.getElementById("TextArea1").value = y.documentElement.innerHTML;


        }
</script>
<input id="Button1" type="button" value="button" onclick="getAndSetContent()" />

但是y.documentElement.innerHTML什么都不返回。我已经尝试了一个本地的html文档,它将在iframe中使用,工作正常。

有什么建议吗?

感谢

1 个答案:

答案 0 :(得分:0)

我假设您的代码正在使用本地文件,因为协议是匹配的,无论如何调试都说明了(您需要一些基本服务器,然后再试一次)。

Uncaught SecurityError: Blocked a frame with origin "null" from accessing a frame with origin "http://www.w3schools.com".  The frame requesting access has a protocol of "file", the frame being accessed has a protocol of "http". Protocols must match.

在服务器上获取代码后,您可能需要使用以下内容来解决问题

https://github.com/padolsey-archive/jquery.fn/tree/master/cross-domain-ajax

相关问题