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.
You’re comparing an element instance with the string
"undefined", and you’re not checking whetherwindow.opener.documentis present (I don’t know whether you have to or not, but it’s easy to add). You probably meant:…except that that’s still not correct, because
getElementByIdreturnsnull(notundefined) when there’s no matching element.Here’s how I’d do it:
That uses the curiously powerful
&&operator (close cousin to the curiously-powerful||operator). The first assignment will short-circuit ifwindow.openerorwindow.opener.documentis “falsey” (nullorundefinedor0or""orNaNor, of course,false— and those last four don’t apply), resulting ininputbeingundefined. The second assignment will short-circuit ifinputis falsey, resulting invaluebeingundefined.undefined!="1", so…