Question

How can I check if I have access to window.opener?

I'm getting an error if I open my page in a new window from a file that is not connected with my page (access denied).

Code:

if (window.opener) {
        if (window.opener.document.getElementById('myHidden') !== "undefined") {
            if (window.opener.document.getElementById('myHidden').value == "1" && $("#inputXYZ").val() != "1") {

In line 2 the error occurs. But only if I open the page from a random page (that of course does not have an input field called "myHidden"). If I open the page from a "valid" page that has such an element, it is working.

Was it helpful?

Solution

You're comparing an element instance with the string "undefined", and you're not checking whether window.opener.document is present (I don't know whether you have to or not, but it's easy to add). You probably meant:

// Note: Still not right, see below
if (typeof window.opener.document.getElementById('myHidden') !== "undefined")

...except that that's still not correct, because getElementById returns null (not undefined) when there's no matching element.

Here's how I'd do it:

var input = window.opener &&
            window.opener.document &&
            window.opener.document.getElementById('myHidden');
var value = input && input.value;
if (value != "1") {
    // Do something
}

That uses the curiously powerful && operator (close cousin to the curiously-powerful || operator). The first assignment will short-circuit if window.opener or window.opener.document is "falsey" (null or undefined or 0 or "" or NaN or, of course, false -- and those last four don't apply), resulting in input being undefined. The second assignment will short-circuit if input is falsey, resulting in value being undefined. undefined != "1", so...

OTHER TIPS

Check if you have access to window.opener.document:

if (window.opener && window.opener.document) {
        if (window.opener.document.getElementById('myHidden') !== "undefined") {
                if (window.opener.document.getElementById('myHidden').value == "1" && $("#inputXYZ").val() != "1") {
                }
        }
}

And if you want to be really sure add in a check for window.opener.document.getElementById e.g.

if (window.opener && window.opener.document && window.opener.document.getElementById) {
        if (window.opener.document.getElementById('myHidden') !== "undefined") {
                if (window.opener.document.getElementById('myHidden').value == "1" && $("#inputXYZ").val() != "1") {
                }
        }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top