Do frames and iframes have isolated javascript contexts?

后端 未结 4 1082
孤街浪徒
孤街浪徒 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 17:51

    It's not "impossible" to share values between frames, but you have to be careful. In Internet Explorer, the following scenario will result in an error:

    1. Create a JavaScript object in frame A.
    2. Pass the JavaScript object to a function in frame B, which saves the value somewhere (in frame B)
    3. Frame A is reloaded with a new page
    4. Code in frame B attempts to reference the saved object from the (former) frame A.

    Internet Explorer does not like it when an object from a defunct page is referenced.

    0 讨论(0)
  • 2021-01-04 18:04

    Yes.

    However, you can use the frames collection or the parent to access other frames (assuming they're from the same domain).

    0 讨论(0)
  • 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/

    0 讨论(0)
  • 2021-01-04 18:09

    The separation of context is not between frames, it is between domains. This means that if you load frame A with domain A and frame B with domain B, javascript from frame A cannot access domain B's context. Check this for a lengthier explanation.

    EDIT: Of course, if they 're on the same domain, the answer provided by SLaks fully applies.

    0 讨论(0)
提交回复
热议问题