Accessing parent window variable from an cross-domain iframe
Inside http://mydomain1.com/index.html
开发者_开发问答<html>
<body>
<script type="text/javascript">
var a = 1;
</script>
<iframe src="http://domain2.com/test2.html"></iframe>
</body>
</html>
Inside http://domain2.com/test2.html
<script type="text/javascript">
alert(parent.a); // forbidden
</script>
Any work arounds?
If you need to communicate with the other frame, you could use postMessage
. This is only available on modern browsers (IE8, FF3, Opera 9, Chrome).
You cannot really have full access to cross domain frames due to the security reasons (Same Origin Policy).
- Reading data cross domain poses security risks because the data on another domain may contain sensitive information (i.e authentication token).
It's possible to post data to another domain. So in this case, maybe you can try:
- domain2.com/test2.html posts a message to mydomain1.com/index.html asking for the "a" value.
- mydomain1.com/index.html when received the message can reply by posting the "a" value to the domain2.com/test2.html
It means you need to set up event listeners on both domains to receive messages posted from another domain.
from the iframe you can access parent DOM nodes, but you cannot do that to parent window variables.
精彩评论