window.open与window.close的兼容性问题

时间:2023-03-08 21:49:03
window.open与window.close的兼容性问题

window.open(页面地址url,打开的方式) 方法 打开一个新的窗口(页面)

如果url为空,则默认打开一个空白页面

如果打开方式为空,默认为新窗口方式打开

返回值:返回新打开窗口的window对象

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<button type="button" id="btn">打开新窗口</button> <script type="text/javascript">
var btn = document.getElementById('btn');
btn.onclick = function(){
var opener = window.open('http://www.baidu.com','_self');
opener.document.body.style.background = 'red'; //不能跨域,只能修改同域名下的。
}
</script>
</body>
</html>

window.close()方法 关闭窗口

关闭默认的窗口是有兼容性问题的:

1、ff:默认无法关闭

2、chrome:默认直接关闭

3、ie:询问用户

关闭在本窗口中通过js方法打开的新窗口是没有兼容性问题的

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<button type="button">打开新窗口</button>
<button type="button">关闭新窗口</button> <script type="text/javascript">
var btn = document.getElementsByTagName('button'),
opener = null; btn[0].onclick = function(){
opener = window.open('http://www.baidu.com','_blank');
opener.document.body.style.background = 'red'; //不能跨域,只能修改同域名下的。
}
btn[1].onclick = function(){
opener.close();
}
</script>
</body>
</html>