且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

从iframe访问父页面中的变量

更新时间:2023-12-01 19:30:46

仅当两个站点来自同一域时,才允许在iframe(和父级)之间交换值。如果他们这样做,那么你的例子应该可行。如果他们不这样做,浏览器会禁止通信。

Exchanging values between iframes (and parent) is only allowed if both sites come from the same domain. If they do, your example should just work. If they don't, browsers inhibit the communication.

然而,有许多黑客可以绕过这个:例如 Julien le Comte的博客使用第三个iframe启用单向通信,或在iframe周围调整iframe大小-idea中描述的 Adam Fortuna的博客实现双向沟通。

However there are a number of hacks to circumvent this: e.g the Yahoo.CrossFrame library described in Julien le Comte's blog using a third iframe to enable one way communication, or the "resize an iframe around the iframe"-idea described in Adam Fortuna's blog enabling two way communication.

编辑(因为人们似乎还在阅读这个旧答案):

在现代浏览器中,您可以使用 postMessage 在iframe之间交换数据。有许多javascript库试图在旧版浏览器中模拟该功能。例如。通过误用location.hash,就像 jquery-postmessage-plugin 那样。

Edit (as people still seem to read this old answer):
In modern Browsers you can use postMessage to exchange Data between iframes. There are many javascript libraries that try to emulate that functionality in older browsers, too. E.g. by mis-using the location.hash, like the jquery-postmessage-plugin does.