您的位置:首页 > 运维架构

window.open的小技巧分享

2015-08-16 21:14 483 查看
%26nbsp; %26nbsp; 今天再次谈起window.open是因为发现了一个比较好玩的小技巧,详细内容我们稍后详细说明。 %26nbsp; %26nbsp; %26nbsp; 聊到window.open,不得不说明一下他的使用方法,主要有两种形式: %26nbsp;
  • window.open()没有任何参数,这种方式可以新标签打开页面
  • window.open(url, name, pars),带有参数的可以在当前页面打开窗口
%26nbsp; %26nbsp; %26nbsp; 详细的使用方法,之前有过介绍,如果想了解,可以点击这里。 %26nbsp; %26nbsp; %26nbsp; 知道了如何使用,接下来介绍几个特别的属性和方法(下面所说到的都是同域页面): %26nbsp;
  1. window.open()打开的窗口或者新标签返回窗口的window对象
  2. 在新窗口里也可以取到父窗口(执行window.open的环境)的window对象,通过window.opner
  3. window.close()方法可以关闭窗口
  4. window.onunload和window.onbeforeunload事件,监听窗口关闭情况
%26nbsp; %26nbsp; %26nbsp; 了解了上面的使用方法之后,介绍一个很巧妙的使用方 4000 式。 %26nbsp; %26nbsp; %26nbsp; 一共有两个页面:第一个页面(window.open.html)的功能是新开一个窗口,第二个页面(window.close.html)为新开窗口的请求的返回信息,可以在第一个页面中,监听新开窗口请求的数据。下面分别介绍两个页面: %26nbsp; %26nbsp; %26nbsp;%26nbsp;window.open.html页面内容如下: %26nbsp;
%26lt;!DOCTYPE%26gt;
%26lt;html%26gt;
%26lt;head%26gt;
%26lt;meta charset="utf-8"%26gt;
%26lt;title%26gt;window.open小技巧%26lt;/title%26gt;
%26lt;/head%26gt;
%26lt;body%26gt;
我是窗口:window.open
%26lt;button id="openWindow"%26gt;点击新开窗口%26lt;/button%26gt;
%26lt;script type="text/javascript"%26gt;
(function() {
var openWindowEl = document.getElementById('openWindow');
var newWindow;
var data;

window.windowName = 'window.open';

openWindowEl.onclick = function() {
newWindow = window.open('window.close.php', '_blank', 'width=500,height=500;');
//需要window.close.html js正常执行之后才行
/*setTimeout(function() {
console.log(newWindow.userName);
}, 1000);*/
newWindow.onbeforeunload = function() {
userName = newWindow.windowName;
data = newWindow.data;
}

newWindow.onunload = function() {
alert(userName);
if(data.errno == 0) {
alert(data.errmsg);
}else {
alert(data.errmsg);
}
}
};
})();
%26lt;/script%26gt;
%26lt;/body%26gt;
%26lt;/html%26gt;
%26nbsp; %26nbsp;   window.close.html页面内容如下: %26nbsp; %26nbsp;%26nbsp;
%26lt;!DOCTYPE%26gt;
%26lt;html%26gt;
%26lt;head%26gt;
%26lt;meta charset="utf-8"%26gt;
%26lt;title%26gt;window新开窗口%26lt;/title%26gt;
%26lt;/head%26gt;
%26lt;body%26gt;
我是窗口:window.close
%26lt;script type="text/javascript"%26gt;
(function() {
window.windowName = 'window.close';
if(Math.random() %26gt; 0.5) {
window.data = {
errno: 0,
errmsg: '成功~'
};
}else {
window.data = {
errno: 1,
errmsg: '数据异常~'
};
}
setTimeout(function() {
//拿到的是父窗口的window
alert(window.opener.windowName);
}, 100);
setTimeout(function() {
window.close();
}, 1000);
})();
%26lt;/script%26gt;
%26lt;/body%26gt;
%26lt;/html%26gt;

%26nbsp; %26nbsp; %26nbsp; 通过上面介绍的这种方式可以解决,微博等第三方登录无刷新父页面得知返回状态的需求。同时也是解决跨域请求的一个比较好的方式(安全性不知道如何)。测试小例子 %26nbsp; %26nbsp; %26nbsp; 今天就分享这么一个小技巧吧~
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: