用window.top === window可以判断出当前页面是不是顶层窗口,而不是嵌套在frame中
但是在IE8下好像不行;
兼容ie8的写法:window.top === window.self
附:
Js中的window.parent ,window.top,window.self 详解
在应用有frameset或者iframe的页面时,parent是父窗口,top是最顶级父窗口(有的窗口中套了好几层frameset或者iframe),self是当前窗口, opener是用open方法打开当前窗口的那个窗口。
window.self
功能:是对当前窗口自身的引用。它和window属性是等价的。
语法:window.self
注:window、self、window.self是等价的。
window.top
功能:返回顶层窗口,即浏览器窗口。
语法:window.top
注:如果窗口本身就是顶层窗口,top属性返回的是对自身的引用。
window.parent
功能:返回父窗口。
语法:window.parent
注:如果窗口本身是顶层窗口,parent属性返回的是对自身的引用。
在框架网页中,一般父窗口就是顶层窗口,但如果框架中还有框架,父窗口和顶层窗口就不一定相同了。
附:
if (window != top) top.location.href = location.href;的意思
如果当前窗口不是最上层窗口(比如是在Iframe中),那么就把自己变为最上层窗口。这可以防止别的网站把你自己的网站放在他的Iframe中,从而损害你的利益(因为会误导浏览者)。
附:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>菜鸟教程(runoob.com)</title>
<script>
function check(){
if (window.top!=window.self) {
document.write("<p>这个窗口不是最顶层窗口!我在一个框架?</p>")
}
else{
document.write("<p>这个窗口是最顶层窗口!</p>")
}
}
</script>
</head>
<body>
<input type="button" οnclick="check()" value="检查窗口">
</body>
</html>