window.parent vs. window opener

I was banging my head against the wall last night trying to get window.parent.location to work and it turns out that window.opener.location is what I wanted to use. Getting to that point was quite a struggle, because searching Google for “window.parent.location” didn’t give me sources with its full description.

Even this morning, searching for “Javascript reference,” I found that normally reputable sources can be wrong. According to the top Google hit for “Javascript reference,” “The parent property returns the parent window of the current window.” That’s what I thought, but that’s not the case.

The next reference in the results makes it more clear: “Reference to the parent frameset window of the current window, assuming current window is a frame. Otherwise, it simply refers to current window.” No wonder I couldn’t get the correct href!

The third reference, from Mozilla’s Developer Network, wasn’t at all what I was looking for in a Javascript reference, or at least that’s what I thought at first glance. In reality, this newbie was looking for the DOM reference, which is linked from that page.

The DOM (“Document Object Model,” for those greener than I) reference on MDN is very complete, with copious notes on each object and its properties. It’s those notes that actually brought me to the site last night, while I was experiencing problems with window.opener.location.

First, I found a bug in Safari 5.0.4 for Mac, where using window.opener.location would cause the browser to crash. The same code in the Firefox also didn’t work, but didn’t crash the browser. This was perplexing to me, because using similar code locally was working.

Fortunately, I knew enough to open the error console in Firefox, which pointed me to this error:

Error: uncaught exception: [Exception... "Could not convert 
JavaScript argument arg 0 [nsIDOMWindowInternal.alert]"
nsresult: "0x80570009 (NS_ERROR_XPC_BAD_CONVERT_JS)" 
location: "JS frame :: http://example.com/script.php ::  
:: line 4" data: no]

Make sense to you? It certainly didn’t to me, or to anyone else I found when Googling the error. But I get banging away at window.opener until I got this error:

Error: Permission denied to access property 'valueOf'
Source File: http://example.com/script.php
Line: 4

Ah! Plain English! And something that, when Googled, led me straight to MDN and this explanation:

A script loaded in a window (or frame) from a distinct origin (domain name) cannot get nor set properties of another window (or frame) or the properties of any of its HTML objects coming from another distinct origin (domain name).

Known as the “Same Origin Policy,” this cross-domain script security restriction was preventing my script from behaving as I expected.

No problem, that’s something I can work around. And I’ve already bookmarked the site as somewhere to look first when I’m needing information on Javascript.