April 4, 2000 - Escaping Frames | WebReference

April 4, 2000 - Escaping Frames

Yehuda Shiran April 4, 2000
Escaping Frames
Tips: April 2000

Yehuda Shiran, Ph.D.
Doc JavaScript

When you create a Web page, you expect the user to load it in the browser's main window, not in another site's frame. By adding a simple cross-browser, cross-platform script into the HEAD portion of your document, you can ensure that the page loads in the entire window. Here's the script:

<SCRIPT LANGUAGE="JavaScript">
<!--
if (window != top) top.location.href = location.href;
// -->
</SCRIPT>

The condition evaluates to true only if window is not equal to top. In other words, if the page's direct window isn't the topmost window in the browser, the condition evaluates to true.

top is the highest window object in the hierarchy. If the topmost page doesn't feature any frames, the object model has only one level of window objects, so top is equal to window. However, if the browser is currently displaying a frame-based document, each child frame has a corresponding window object.

Note that the following expressions would also function properly:

window != parent
self != top

Back to the script. If the page's window isn't the topmost window in the object model, your page is being displayed as a frame in a frame-setting document. In order to escape the frames, you need to set the URL of the upper window to the URL of the current page:

if (window != top) top.location.href = location.href;

Learn more about frames in Column 36, JavaScript and Frames, Part I .