views:

32

answers:

3

I have a JS Object called CoolThing that exists in the top window.

I have an iFrame, same domain as top window, that needs to access a property, CoolProperty, in CoolThing.

The javascript in the iFrame to access CoolProperty, which works perfectly in FF, webkit, and IE8, is:

<script type="text/javascript" charset="utf-8">
  with(window.parent) {
    this.CoolThing.CoolProperty.coolFunction();
  }
</script>

In IE7, i get the error: this.CoolThing.CoolProperty is null or not an object. I've tried inspecting CoolThing by iterating through its properties, but there are none according to IE7. It has no problem accessing this.CoolThing itself.. only it seems to think the object is empty.

I've tried the above without the with statement and attempted calling window.parent.CoolThing.CoolProperty directly, which, again, has no problem executing in all browsers except for IE7, in which it gives the same error.

Any tips?

+1  A: 

This works for me:

Parent page script:

<script type="text/javascript">
var CoolThing = { CoolProperty:function() { alert("foo alert");} };
</script>

Child page script:

<script type="text/javascript">
    with (parent)
    {
        CoolThing.CoolProperty();
    }
</script>

Based on further reading, I would recommend not using with() at all and just use the following in the child page:

<script type="text/javascript">
    parent.CoolThing.CoolProperty();
</script>
David
unfortunately, I gave a very simplified example that doesn't really show why we're using with, and it is to get at 'this', which we are using to scope properties, as well as jquery calls. As it turns out I am able to call the function I want without using with (I thought I had attempted this already and it did not work, but now it seems to), so I'm just rewriting the code without the with block. FWIW, 'with' let us write some damn elegant code, and we would have gotten away with it if it weren't for pesky IE7.
jwubs
A: 

Actually, according to an interesting discussion on SO, the with keyword does change the scope, and that is one reason for using it. IE7 may behave differently.

Robusto
Yes, but only for finding existing members, not for declaring new members, so it really is dangerous for the purposes of changing "scope".
David
@David: Agreed. I just thought the discussion was interesting and germane, so I included the pointer to it.
Robusto
Thanks for posting the link, I learned from it.
David
A: 

Why not just

parent.coolThing.coolWhatever();

Or if you insist on using with:

with(parent) {
    coolThing.etCetera();
}
jasongetsdown