Could this easily be made to work with any number of widgets (in a dynamic fashion) rather than just two widgets? Or would every widgets name have to be hard-coded into the function and placed into each available widget?
No, you could setup a listener for the app event that opens widget and then use the sample testOpenClose in the viewer to see how to check for any open widgets and fire off the close widget event for any that are open.