javascriptdomframes

What does comparing `self` to `top` do in JavaScript?


if (self != top) {
  window.open(self.location,'_top');
}

What does self != top and window.open(self.location, '_top'); mean respectively?


Solution

  • This will break out of a HTML frame and replace the top-level frame by the current page.

    It's akin to clicking a link with target="_top" set which will throw away the complete frameset and replace it with the page that link points to. It's exactly what that code does by simply "opening a link" (in user terms; in JavaScript it takes the form of window.open) to the very same page we're seeing, but at the top level.

    self in this respect is the page we're currently in. top is the top-level frame the browser is displaying. If the browser doesn't display a frameset, then self == top holds. If however, our page is framed, then they will be different.

    So self != top detects if the page is displayed in a frame and window.open is, as noted before, just like clicking on a link with the target attribute set to "_top" (the second argument.