从iframe访问父页面中的变量 [英] accessing variable in parent page from iframe

查看:125
本文介绍了从iframe访问父页面中的变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含html页面的iframe页面。我想从iframe中访问父页面中的Javascript变量。主页面中变量的名称是 observer

I have a page with an iframe that contains a html page. I want to access a Javascript variable in the parent page from within the iframe. The name of the variable in the main page is observer.

我试过这个

parent.observer = 'aadasds';

但我收到以下错误:

获取属性的权限Window.observer
来自

Permission denied for to get property Window.observer from

推荐答案

仅当两个站点来自同一域时,才允许在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.

这篇关于从iframe访问父页面中的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆