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

Yehuda Shiran, Ph.D.
Doc JavaScript

Developer News
News Flash: Adobe Has iPhone Workaround
Adobe's Flash 10.1 Goes Mobile (Minus iPhone)
A Salute to Visionary CEOs

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, Reprints, Permissions, Privacy Policy.
Advertise | Newsletters | Shopping | E-mail Offers | Freelance Jobs

webref The latest from WebReference.com Browse >
Building a Banking Application Home Page with OOP · Mixing Scripting Languages · Review: phpFox, a Social Networking CMS with all the Bells and Whistles
Sitemap · Experts · Tools · Services · Email a Colleague · Contact FREE Newsletters 
 The latest from internet.com
Enterprise 2.0: Social Networking in the Cloud · BroadSoft Marketplace Hastens Pace of Telephony Innovation · Review: HTC Hero for Sprint