如何从父页面访问 iframe 的 javascript 对象?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8296141/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to access iframe's javascript objects from parent page?
提问by Dims
Is it possible to access iframe's javascript objects from javascript of parent page?
是否可以从父页面的 javascript 访问 iframe 的 javascript 对象?
回答by erimerturk
Try this. I assume your iFrame's id is "targetFrame"
and the object you want to call is targetObject
and also they are same domain. If they are not same domain I think it is not possible.:
试试这个。我假设你的 iFrame 的 id 是"targetFrame"
,你想调用的对象是targetObject
,而且它们是同一个域。如果它们不是同一个域,我认为这是不可能的。:
document.getElementById('targetFrame').contentWindow.targetObject
回答by Ben
If the iframe src is not in the same origin/domain as the parent you'd have restrictions
如果 iframe src 与父项不在同一个源/域中,您将受到限制
because of the same-origin-policy (security policy) https://developer.mozilla.org/en/Same_origin_policy_for_JavaScript
由于同源策略(安全策略) https://developer.mozilla.org/en/Same_origin_policy_for_JavaScript
The policy is planned to block accessing private data such as CSRF tokens and other Private data stored in the frame, for example if you build an html page with an iframe of bank.com then when people get into your site if they are logged into bank.com their private data will be stored in the iframe for that reason same-origin-policy will block different origins from accessing eachother's data through iframes.
该策略计划阻止访问私有数据,例如 CSRF 令牌和存储在框架中的其他私有数据,例如,如果您使用 bank.com 的 iframe 构建 html 页面,那么当人们登录银行后进入您的站点时.com 他们的私有数据将被存储在 iframe 中,因此同源策略将阻止不同来源通过 iframe 访问彼此的数据。
回答by SHANK
You can also access the objects of child iframe using the parent's window object.
您还可以使用父级的 window 对象访问子 iframe 的对象。
alert( window.frames[0].variable_name );
It will show the value of variable, variable_name, from the first iFrame. The index of frames list can be used to access the values of variables across frames.
它将显示第一个 iFrame 中变量 variable_name 的值。帧列表的索引可用于访问跨帧的变量值。