Home >Web Front-end >JS Tutorial >Function window.open closes all child windows_javascript skills
This article introduces how to use the window.open method to open a sub-window. When we close the main window, all sub-windows will also be closed. Below are my implementation ideas and code to share with you.
Implementation ideas:
1. The second parameter winName of the open child window function window.open(url,winName) can uniquely identify the open window. Therefore, you only need to use the winName.close() function to close the child window.
2. A page may have multiple sub-windows. Therefore, an array is needed to store all child window objects. When closed, just iterate through the array.
3. Sub-windows can also open sub-windows. The loop continues indefinitely. Hence the need for judgment.
This requirement can be achieved in two ways.
Call the closing function of the child window.
This method is easy to understand, but during the actual implementation process, it was found that the browser's closing event did not occur. And it needs to be closed by clicking a button or using a shortcut key. It is a little more troublesome to close the sub-window recursively
This method is simple to implement. The disadvantage is that all window object arrays that store sub-windows need to have the same name
The following is a sub-window method that uses recursion to close sub-windows and sub-windows
function closeSonWindow(win){ for(var index=0;index<win.length;index++){ //如果窗口已关闭 if(win[index].closed){ continue; } //如果窗口没有可以打开的子窗口 if(typeof(win[index].openedWindow)=="undefined"){ win[index].close(); continue; } if(win[index].openedWindow.length==0){ win[index].close(); }else{ closeSonWindow(win[index].openedWindow); win[index].close(); } } }
The above is the entire description of this article, I hope it will be helpful to everyone.