1

I have the following code in Internet Explorer 8:

if (window.opener != null && window.opener.foo != null)  window.opener.foo = bar;

Sometimes, window.opener is set. But if users open a popup and then navigate away, the attempt to set a property on it should be avoided.

In Firefox and Chrome, this works, because window.opener becomes null once the user exits or refreshes that window. In IE, however, window.opener is not null, and window.opener.foo gives "Permission Denied" instead of null. Because of this, window.opener.foo != null evaluates to true.

How do I get around this problem, what value matches "Permission Denied" in Internet Explorer?

Andrew Latham
  • 5,982
  • 14
  • 47
  • 87

2 Answers2

1

This is the check I use in IE8:

if (window.opener && !window.opener.closed) {
    // do what you will with window.opener
}

Edit: if you want to display a friendly error, you can try something like this:

try {
    if (window.opener && window.opener.foo != null) {
        window.opener.foo = bar;
    }
} catch (e) {
    if (e.description.toLowerCase().indexOf('permission denied') !== -1) {
        // handle it nicely
    } else {
        // some other problem, let it blow up
        throw e;
    }
}

This allows you to specifically handle the "Access Denied" error, while not hiding any other potential errors.

jbabey
  • 45,965
  • 12
  • 71
  • 94
  • @AndrewLatham if the user refreshes the page then the window is closed, as it should be. what are you trying to accomplish? – jbabey Oct 25 '12 at 17:58
  • In IE8, for me, refresh resulted in it still thinking window.opener. closed was false. I'm trying to access a property of the parent page in a popup while showing an error message if permission is denied (which would be the case if the parent page was refreshed or exited). In Firefox/Chrome, I can detect this by checking if window.opener is null. – Andrew Latham Oct 25 '12 at 18:02
  • Basically, I want to be able to find out if permission was denied without doing a try-catch, which could be anything. – Andrew Latham Oct 25 '12 at 18:16
  • @AndrewLatham see my edit, it's not pretty but it may be the only way. – jbabey Oct 25 '12 at 18:25
  • Fair enough, I came to the same conclusion. – Andrew Latham Oct 25 '12 at 18:36
0

If you don't have access to the properties of window.opener in IE, then passing it to Object.keys() will return a 0 length string.

Example usage:

if (window.opener && Object.keys(window.opener).length) {
  // do what you will with window.opener
}