【发布时间】:2013-02-12 10:48:35
【问题描述】:
#ontop {
position: absolute;
width: 100%;
height: 10%;
top: 0;
bottom: 90%;
background-color: yellow;
}
#content {
position: absolute;
width: 100%;
height: 90%;
top: 10%;
bottom: 0;
border: 0;
}
鉴于上述 CSS,是否可以在 #content DOM 元素中加载外部网站以允许用户浏览它? #ontop 元素将能够向当前加载的网站提出一些附加功能。
iframe 通常表现得如我所愿:
<div id="ontop">Always on top</div>
<iframe id="content" src="http://en.wikipedia.org/"></iframe>
出于安全考虑,一些网站(例如 Stack Overflow)避免访问 iframe 中的内容。
<div id="ontop">Always on top</div>
<iframe id="content" src="http://www.stackoverflow.com/"></iframe>
上面的 sn-p 不会加载网站内容,同时抛出以下错误:refused to display document because display denied by X-Frame-Options.
然后我尝试使用 AJAX 来满足我的需求(请参阅 this mod 以允许使用 jQuery 进行跨域 AJAX 请求):
<script type="text/javascript">
$(function() {
$.ajax({
url: 'http://www.stackoverflow.com/',
type: 'GET',
success: function(data) {
$("#content").html(data.responseText);
}
});
});
</script>
<div id="ontop">Always on top</div>
<div id="content"></div>
这几乎有效,因为出现了两个问题:
- 复杂网站(如 Stack Overflow)的渲染失败;
- 用户无法浏览加载的网站,因为 URL(例如链接、请求)现在与运行上述脚本的服务器相关。
我终于尝试将前两种解决方案结合起来:
<script type="text/javascript">
$(function() {
$.ajax({
url: 'http://www.stackoverflow.com/',
type: 'GET',
success: function(data) {
$("#content").contents().find('body').append(data.responseText);
}
});
});
</script>
<div id="ontop">Always on top</div>
<iframe id="content"></iframe>
这有点好:
- 渲染失败更少(例如,Google 仍然搞砸了,而 Stack Overflow 不再出现);
- 网址仍然错误。
如何实现我的目标?无论是管理这些相对 URL 的解决方案,还是仍然适合我需要的完全不同的解决方案,都将受到欢迎。
由于jsFiddle对于这种复杂的异步请求还不够强大,下面是我提供的三个尝试的源码:
- 使用
iframe:iframe.html - 使用 AJAX:ajax.html
- 同时使用:both.html
【问题讨论】:
-
好久没看到详细的问题/情况了。
标签: javascript html css ajax iframe