Closing children windows from Javascript
-
24-05-2021 - |
문제
I have been searching high and low for a solution to my problem and can only find pieces of the puzzle with no way to connect them. I have a window (which it self is a child of the main window) that can open multiple other windows. I want the children windows to be closed when the parent is closed, sounds simple enough right?
Here is the dilemma, my parent window does a postback when opening the child so any array of handles (which are also objects) I keep does not persist. I have looked into serializing and de-serializing this array and storing it in a hidden field but that doesn't seem like the best solution. I also can not access the parent of the window doing the opening.
Aside from Javascript, the server side code is written in C# and I'm using asp.net. Is there any reasonable solution to this? I should also mention that the code I am working with was written by multiple different people long before I got to it so I would like to add to it rather than changing how most of it works.
Finally, I know it is typically a good idea to post my code on here but I am simply using var win = window.open
to perform the window opening task.
Thank you.
해결책
OK, I then see 3 ways to get around that problem:
- Don't use multiple browser windows, but style your page to show all the dialogues; as @Gats suggested. OK, that will somewhat limit you if you want the input of parent "windows" persistant while navigating in a child window.
- Don't do a refresh postback to unload the parent. Use Ajax instead to send data to the application server
- You can't store (window) objects, you only can store strings. When opening a window, you can give it a "target" name, and any other
window.open
with the same target (name) will use the already open one. With that, you can reference windows you didn't open yourself - and close them. See https://stackoverflow.com/a/563478/1048572
다른 팁
What about
var wins = [];
function newChildWindow(...) {
wins.push(window.open(...));
}
window.onuload = function() {
for (var i=0; i<wins.length; i++)
if (!wins[i].closed)
wins[i].close();
};