javascript关闭子窗口
最近项目中要用到js关闭所有打开的子窗口,包括window.open打开的和<a href="" target="_blank">超链接打开的窗口,父窗口关闭,所有的子窗口自动关闭
javascript代码如下(c.js):
var subWin = null;var subWinList = new Array();function showWin(){ if (!document.getElementsByTagName) return false; var links = document.getElementsByTagName("a"); for ( var i=0; i < links.length; i++) { links[i].onclick = function(){if(this.getAttribute('target')=='_blank' ) { subWin = window.open(this.getAttribute('href')); subWinList.push(subWin); return false;}} }}function openwindow(url,name,iWidth,iHeight){ var url; var name; var iWidth; var iHeight; var iTop = (window.screen.availHeight-30-iHeight)/2; var iLeft = (window.screen.availWidth-10-iWidth)/2; subWin=window.open(url,name,'height='+iHeight+',innerHeight='+iHeight+',width='+iWidth+',innerWidth='+iWidth+',top='+iTop+',left='+iLeft+',toolbar=no,location=no,status=yes,scrollbars=yes,resizable=yes,directoried=no,menubar=no');subWinList.push(subWin);}function closeChild(){if (subWin && subWin.open && !subWin.closed){subWin.close();}for(i=0;i<subWinList.length;i++){subWinList[i].close();}}window.attachEvent("onload",showWin);window.onunload=closeChild;
<html><head><script type="text/javascript" src="c.js"></script></head><body><a href="b.html" target="_blank">hello</a><a href="b.html" target="_blank">hello</a><a href="b.html" target="_blank">hello</a><a href="b.html" target="_blank">hello</a><a href="b.html" target="_blank">hello</a><a href="b.html" target="_blank">hello</a><a href="b.html" target="_blank">hello</a><a href="b.html" target="_blank">hello</a><a href="b.html" target="_blank">hello</a><input type="button" name="sub" value="打开新窗口" onclick="openwindow("b.html","",500,600)"></body></html>