*sigh* I wish this were that simple. getMostRecentWindow()/getEnumerator() can return windows that are closed/in the process of being closed. Yes, it is stupid. On top of that, getZOrderDOMWindowEnumerator() is most accurate to get the z-order... but that doesn't work right on Linux/OSX :(

Could probably get away with ignoring getZOrderDOMWindowEnumerator(), but at the very least you do need to take into account closed windows (we've had numerous bugs in Firefox in the past due to this). See here for the most safe version of the algorithm:
https://mxr.mozilla.org/mozilla-central/source/browser/components/sessionstore/src/SessionStore.jsm#3776