8

So the following code alerts false twice:

window.onload = function(){
                    alert(window.myframe.myarray instanceof Array);
                    alert(window.myframe.myarray.constructor === Array);
                }

When there's an iframe in the page named "myframe" that has contains an array called "myarray". If the array is moved into the main page (as opposed to the iframe), then the code alerts true twice as expected. Does anyone know why this is?

zjmiller
  • 2,709
  • 4
  • 29
  • 30
  • 1
    What does window.myframe.myarray print? I thought you need it to be window.myframe.document.myarray – Amir Raminfar Jun 24 '11 at 20:16
  • window.myframename.myarray works fine in Chrome and FF... document.getElementById('myframeid').contentWindow.myarray also works... what you're suggesting doesn't seem to work... – zjmiller Jun 24 '11 at 20:21
  • err I meant window.myframe.contentWindow.document.myarray – Amir Raminfar Jun 24 '11 at 20:26
  • hmm that doesn't work either... I think you use what you have if you're trying to access a DOM node as opposed to JavaScript variables/objects? – zjmiller Jun 24 '11 at 20:29

2 Answers2

19
function isArray(o) {
  return Object.prototype.toString.call(o) === '[object Array]';
}

Long explanation here about why .constructor fails with frames.

The problems arise when it comes to scripting in multi-frame DOM environments. In a nutshell, Array objects created within one iframe do not share [[Prototype]]’s with arrays created within another iframe. Their constructors are different objects and so both instanceof and constructor checks fail:

epascarello
  • 204,599
  • 20
  • 195
  • 236
  • This is exactly what the problem is. – Pointy Jun 24 '11 at 20:24
  • Still there is a chance that you have to fall back to duck typing cos libraries can overload the toString easily (like if you load [shumway](https://github.com/mozilla/shumway/blob/master/src/avm2/runtime.ts#L1024-L1060): `Object.prototype.toString.call([1,2,3]) === '1,2,3'` ) – Pengő Dzsó Mar 21 '14 at 14:18
5

The two windows each create their own global script environment.

The Array constructor of one is not the same object as the other.

var win2=window.myframe;
alert(win2.myarray instanceof win2.Array); returns true
kennebec
  • 102,654
  • 32
  • 106
  • 127