thomasvdb
thomasvdb

Reputation: 749

Javascript variable changes in Internet Explorer unexpectedly

Let us start with the Javascript-code:

<script type="text/javascript">
var parentWindowLocation = '';

// closes the popop of the search when the parent is closed
window.onload = function() {
    parentWindowLocation = window.opener.location;

    if (window.opener != null) {
        setInterval("checkParentExists()", 5000);
    }
}

function checkParentExists() {
    try {
        alert(window.opener.location);
        alert(parentWindowLocation);
        if (window.opener == null || window.opener.closed) {
            window.close();
        } else {
            if (parentWindowLocation != window.opener.location) { window.close(); }
        }
    } catch (e) { window.close(); }
}
</script>

The code above is specified in a popup. The popup should close itself when the parent is closed or if the URL of the parent has changed. This works perfectly in Firefox and Chrome but not in Internet Explorer.

I've added the two alerts in checkParentExists() to see what happened in Internet Explorer. I noticed that when the parent changes to a different URL (so window.opener.location changes) the variable parentWindowLocation is also set to the new URL of the parent! I only set the variable in window.onload so what happened?

Upvotes: 1

Views: 327

Answers (2)

mplungjan
mplungjan

Reputation: 177796

Do this in the parent:

var childWin;
window.onbeforeunload=function() {
  try {
    if (childWin && !childWin.closed()) childWin.close();
  }
  catch(e) {}
}
.
.
.
childWin=window.open(....);

Upvotes: 0

Pointy
Pointy

Reputation: 413720

The "location" object is, well, an object. When you convert it to a string, you get something made from the properties of the object, but it's not a string. Thus, your variable can still refer to the "location" object, but the value can change.

If you set your variable to window.opener.location.href instead, you'll get a string. You could also try this:

     parentWindowLocation = window.opener.location + '';

which will also force it to be "captured" as a string.

Upvotes: 3

Related Questions