How to close all open popup windows on logout action?
Many Web applications I have seen/worked before use HTML popup windows to handle editor/add new screens. But unfortunately there are many issues (lack of modal dialog support for example) with popups and hence using them should be the last option.
How do you close all the popup windows when user clicks on the “logout” link in the main page? I had hoped that there would be some collection in the window object which keeps track of the popups opened from it. But unfortunately there is no such thing. You can use window.opener to find the instance of the parent window, but not the other way around. The only option is to keep track of the popup windows generated using JavaScript.
Following is the approach I have taken. It is not perfect, but so far I haven’t come across any major issues. But if your application is already built and has a lot of window.open() calls, the following approach will affect a lot of source files.
1. Encapsulate window.open() method in a custom application method such as appShowPopup(). The method signature can be same as window.open. This is an important design technique. Whenever you access an important API, it makes sense to wrap it using a application level custom API.
var gblPopupArray = new Array(); function appShowPopup(url,name,features) { for(var i=0;i<gblPopupArray.length;i++) { try { if(name==gblPopupArray[i].name) { gblPopupArray[i] = window.open(url,name,features); return; } } } gblPopupArray[gblPopupArray.length]=window.open(url,name,features); }
2. Inside appShowPopup() keep a track of all the popup windows using a global page level JavaScript array. Ensure that every popup window is named properly using the second argument. Before adding a popup instance check whether there are any instances in the array with same name. If there is one, replace it (instead of adding a new instance to array).
3. On logout, use the popup window array to close all popups. You will need to check the existence of a window before closing. An easier way will be to put the close() code in a try catch block.
function closeAllPopups() { for(var i=0;i<gblPopupArray.length;i++) { try { gblPopupArray[i].close(); }catch(ex) {} } gblPopupArray = new Array(); }