spacer
Yehuda Shiran May 11, 2000
Checking for a Window's Existence
Tips: May 2000

Yehuda Shiran, Ph.D.
Doc JavaScript

Developer News
Microsoft Shows Off Silverlight 4, IE9 Plans
Metasploit Expands Vulnerability Test Framework
HyperCard Reborn?

So you know the browser actually created the new window. But does it still exist? Not necessarily. You need to make sure the window variable holds a real window object. Since every window object features an open() method, you can detect the method via object detection:

// if win.open exists, move the window
if (win.open) win.moveTo(0, 0);

The variable win reflects the window object of the window, so win.open references the window's window.open() method. Notice that the conditional expression is a function reference (without parentheses), not a function call. You shouldn't attempt to evaluate win.open unless you know for sure that win exists. The following statement demonstrates the correct implementation:

// if win and win.open exist, move the window
if (win && win.open) win.moveTo(0, 0);

Since && is a short-circuit operator, it only evaluates its second operand (win.open, in this case) if the first one (win) reflects a true value. If the first operand evaluates to false, the entire expression is obviously false, so JavaScript doesn't even look at the second operand. This is an important behavior, because the expression win.open generates an error if win doesn't exist.


People who read this tip also read these tips:

Look for similar tips by subject:

internet.commediabistro.comJusttechjobs.comGraphics.com

Search:

WebMediaBrands Corporate Info

Legal Notices, Licensing, Permissions, Privacy Policy.
Advertise | Newsletters | Shopping | E-mail Offers | Freelance Jobs

webref The latest from WebReference.com Browse >
Rolling Out Your Own HTML Application Version Control · HTML 5: Client-side Storage · Working with Ajax Server Extensions
Sitemap · Experts · Tools · Services · Email a Colleague · Contact FREE Newsletters 
 The latest from internet.com
Wi-Fi Product Watch, November 2009 · Chip Market Recovering From '08 Collapse · Low-Cost Tools to Kickstart Your New Business