TLDR; In theory, it can't be done. In reality, you can always find a way around it.
Why can't we store a reference to a window
When refreshing a page, you lose the ability to keep an actual reference to a window (i.e. an Object with the methods associated), because the only place for you to store it would be in cookies, or localStorage. But these only allow you to store string representations of your data. Thus, once the page is reloaded, you cannot use these window
elements anymore. (Even if you could store actual Objects, they would be useless copies - not full-fledged circular Objects such as window
)
A way around it
I found your question interesting, so I gave it a try with this Proof of Concept:
Two types of pages
A Master page will be able to open Slave pages. It will also be able to close them as long as you don't refresh it. But if you do, you'll need to find a way to leave them messages for letting them know they should be closed.
Leave a note on the fridge
Here, our fridge will be the localStorage
. When a slave page is open, it adds a post-it note to the fridge, giving its Id, and its status. This post-it can be accessed and modified by the master page. Periodically, each slave will check its associated post-it, and see if it should close itself or not.
An algorithm you could create
This pseudo code shows how you could do it, in a simple manner.
Master page script
// If the page was simply refreshed, we want to cancel our
// post-it modifications before they take effect
when (window_is_loaded) :
cancel_previous_postit_modifications()
when (open_slaves_button_is_clicked) :
open_slaves()
// Here, we know we can close the slaves
when (close_slaves_button_is_clicked) :
tell_slaves_to_close()
// Here, we don't know whether this is a refresh or not,
// So we tell them to wait, and close if they don't here back from us
when (window_is_being_unloaded) :
tell_slaves_to_close_after_delay()
Slave page script
when (window_is_loaded) :
create_postit_note()
when (window_is_being_unloaded) :
remove_postit()
every (X milliseconds) :
if (status_on_postit_is('willBeClosed')) :
change_status_to('shouldBeClosed')
else if (status_on_postit_is('shouldBeClosed')) :
close_window()
Test code
To check if this is possible, I created a test project:
Full code: https://github.com/blex41/slave-windows
Live demo: Here