IFrame
是一个分享资讯非常方便的的方式
只要输入
<iframe src="http://example.com/"></iframe>
就可以嵌入一个网页了!
然而,事实上并不是这么的完美,并不是所有的网页都允许嵌入…
譬如说Google,如果妳直接就输入Google 的网址,如下面
<iframe src="http://google.com"></iframe>
那么将只会得到一个空白的IFrame
而已…
如果有打开Console 的话,就会看到一些安全性上的错误,不过很可惜的JavaScript 很难去handle 这个错误…
针对IFrame
监听onerror是没用的,因为根本没有这个事件!
那么如果针对window.onerror
呢?
可以捕捉到错误,但是却不能判断到底能不能载入…(即便是可以嵌入的网站,也会有一些错误讯息出现)
最后如果针对IFrame
监听onload如果网站可以嵌入,就会触发这个 事件,如果不能嵌入就不触发
问题是,网站何时还会触发onload 事件呢? 如果用setTimeout
解的话,到底要设定多久呢?
怎么设定都会有问题,那么究竟该怎么样才可以准确的呈现出此网页不允许嵌入的资讯给User 看呢?
要针对几个IFrame
的特性来解决这个问题
- 当
IFrame
的src
的网址是允许嵌入的话,会把网页呈现出来 - 当
IFrame
的src
的网址是不允许嵌入的话,是不会改变目前的画面的 - 当
IFrame
没有给定src
时,内容是空白的
另外,有一个url
非常的特别,那就是about:blank
,这个url
就是全白的内容,连HTML
都没有
但是parent的JavaScript是可以操纵该IFrame
的内容的!
要怎么做就呼之欲出了!
- 把
IFrame
的src
设定为about:blank
- 监听
IFrame
监听load
事件,并且在callback
中要处里几件事情
- 当中把先把错误讯息埋好
- 在把
IFrame
的src
换成要嵌入的url
- 取消监听
IFrame
的load
事件
- 看成果!
如果url
是不允许被嵌入的,就会看到错误讯息,反之则是正确的结果!
最后看范例吧…
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JS Bin</title>
<style>
#ifr { border-width: 0;opacity: 0; transition: .5s;};
</style>
</head>
<body>
<div>
<button id="google">Google</button>
<button id="yahoo">Yahoo</button>
<button id="jcluo">Jcluo</button>
</div>
<iframe id="ifr" ></iframe>
</body>
</html>
var ifr = document.querySelector('#ifr');
ifr.onload = function () {
if (this.getAttribute('is-reset') == '1') {
this.style.opacity = 0;
this.style.display = 'block';
this.contentDocument.write("Can't not load Web");
var url = this.getAttribute('src-url');
this.setAttribute('src', url);
this.setAttribute('is-reset',0);
} else {
this.style.opacity = '1';
}
};
function changeUrl(url) {
ifr.style.display = 'none';
ifr.setAttribute('is-reset',1);
ifr.setAttribute('src', 'about:blank');
ifr.setAttribute('src-url', url);
}
document.querySelector('#google').onclick = function () {
changeUrl('http://www.google.com');
}
document.querySelector('#yahoo').onclick = function () {
changeUrl('http://www.yahoo.com');
}
document.querySelector('#jcluo').onclick = function () {
changeUrl('http://blog.jcluo.net');
}
范例代码地址:http://jsbin.com/mijicuhobemo/3/embed?html,css,js,output
此范例由voluntariness所撰写