Do frames and iframes have isolated javascript contexts?

后端 未结 4 1084
孤街浪徒
孤街浪徒 2021-01-04 17:27

I\'ve made some experiments in Chrome but I\'m not sure so I need a confirmation :

Am I correct in thinking that iframes and frames have a separate JavaScript contex

4条回答
  •  隐瞒了意图╮
    2021-01-04 18:08

    Well, they just have different global objects and global scope. However, if they are in the same domain you can run code in one from another. But if you were to do this (inside parent window):

    document.getElementById( "myiframe" ).contentWindow.window.globalArray = [];
    

    Which creates a global variable globalArray inside the iframe's global scope.

    and then inside the iframe

    console.log( globalArray instanceof Array );

    will return false because Array refers to the iframe's Array constructor. You'd have to do

    console.log( globalArray instanceof top.Array );
    

    where top refers to the container window global object.

    jsfiddle: http://jsfiddle.net/EFbtN/

提交回复
热议问题