Are there isolated javascript contexts in frames and iframes?

I did some experiments in Chrome, but I'm not sure, so I need confirmation:

Do I correctly assume that iframes and frames have a separate JavaScript context, which makes it impossible to share variables between these frames / iframes?

To simplify, let's say that the client will always be the same version of Chrome (this is my case)

+6
source share
4 answers

Yes.

However, you can use the frames or parent collection to access other frames (provided that they are from the same domain).

+8
source

It is not possible to "exchange" values ​​between frames, but you must be careful. In Internet Explorer, the following script will result in an error:

  • Create a JavaScript object in frame A.
  • Pass the JavaScript object to a function in frame B that stores the value somewhere (in frame B)
  • Frame A reloads with a new page
  • The code in frame B tries to refer to a stored object from (former) frame A.

Internet Explorer does not like it when it refers to an object from a page that does not exist.

+6
source

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

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

Which creates the global variable globalArray inside the global iframe.

and then inside the iframe

console.log( globalArray instanceof Array );

will return false because Array refers to the iframe constructor of the Array . You will need to do

 console.log( globalArray instanceof top.Array ); 

where top refers to the global container window object.

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

+3
source

The separation of context does not occur between frames, but between domains. This means that if you load frame A with domain A and frame B with domain B, javascript from frame A will not be able to access the context of domain B. Check this for a more detailed explanation.

EDIT: Of course, if they are in the same domain, then the answer provided by SLaks fully applies.

+1
source

Source: https://habr.com/ru/post/902020/


All Articles