Search code examples
javascriptwindow.opener

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


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.


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...