Search code examples
javascripthttp-redirectwindowlanguage-lawyer

Can the default `window.top` ever be invalid as a reference?


I want to redirect the user to an external page and simultaneously break out of a frameset.

The outermost frameset is most likely within the same domain as the page doing the redirection, but there is the possibility that it will span domains. In development, the outermost frameset might not even exist at all. Ideally, I want to cover all those situations.

The innermost page (the one that has the breakout code) is going to be served over HTTPS. The target URL may be HTTP or HTTPS. It is acceptable for the redirection to fail (there is a fallback link "click here to continue" to cover for that scenario) but the redirection should work in the majority of cases. Particularly for the purposes of this question, I'd hate for it to be more browser-dependent than necessary.

The web application itself is ASP.NET.

Because of the framesets, I can't simply use a HTTP redirect.

So far I have this Javascript code, which is registered as a startup script from within a class subclassing Page, where ... represents the redirection target URL:

((window.top == null) ? (window) : (window.top)).location = '...';

What bothers me is what MDN has to say about window.top and window.parent, respectively. Particularly, the documentation for window.parent spells out explicitly that

If a window does not have a parent, its parent property is a reference to itself.

which means that I can assert window.parent != null. But there is nothing similar about the value of window.top.

For the purposes of my question, you can assume that neither of these have been reassigned.

All that to lead up to the actual question: Does window.top make guarantees similar to that of window.parent? (I'm a bit concerned about the conditional expression. In my so far limited testing it works, but that doesn't prove it correct.)

As far as I can tell, at least MDN doesn't say for certain either way.


Solution

  • The HTML5 spec defines window.top like so:

    The top IDL attribute on the Window object of a Document in a browsing context b must return the WindowProxy object of its top-level browsing context (which would be its own WindowProxy object if it was a top-level browsing context itself), if it has one, or its own WindowProxy object otherwise (e.g. if it was a detached nested browsing context).

    So the top attribute must always refer to a window. The spec also defines top as readonly so it is not posisble to change it to point to something else (if the spec is implemented properly).

    Something is very bad if window.top == null!