与该页面内的 iframe 共享页面的全局 javascript 变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7647042/
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
Sharing global javascript variable of a page with an iframe within that page
提问by Ankit
I have an scenario where in I have a page, which have <script>
tag and some global javascript variables within that. I also have an iframe within that page and I want to have access of global javascript variables of the page in iframe.
我有一个场景,其中有一个页面,其中包含<script>
标签和一些全局 javascript 变量。我在该页面中还有一个 iframe,我想访问 iframe 中页面的全局 javascript 变量。
Is it possible?, if yes, how can i do that?
有可能吗?,如果是,我该怎么做?
回答by Jan Pfeifer
Easily by calling parent.your_var_name in your iframe's script.
通过在 iframe 的脚本中调用 parent.your_var_name 很容易。
One condition: both pages (main and iframe's) have to be on the same domain.
一个条件:两个页面(主页面和 iframe 的)必须在同一个域中。
main page:
主页:
<script>
var my_var = 'hello world!';
</script>
iframe
内嵌框架
<script>
function some_fn(){
alert(parent.my_var); //helo world!
}
</script>
回答by Alain Beauvois
Not possible ifthe iframe and the main document are not in the same domain (due to cross domain security policy).
如果iframe 和主文档不在同一个域中(由于跨域安全策略),则不可能。
To bypass this limitation you can use cross domain messaging.
要绕过此限制,您可以使用跨域消息传递。
Possible ififrame an main document are in the same domain, you can access their global variables. There are object which belongs to the window object of the iframe or the main page.
如果iframe 一个主文档在同一个域中,则可以访问它们的全局变量。有属于 iframe 或主页的 window 对象的对象。
Here is the code to access the iframe variable myvarfrom the main document (or an iframe) in a same domain:
这是从同一域中的主文档(或 iframe) 访问 iframe 变量myvar的代码 :
document.getElementById('iframeid').contentWindow['myvar'];
回答by Panu Logic
Great answers above. Just to add, beware of this in ES6:
上面的答案很好。补充一点,在 ES6 中要注意这一点:
<script>
const my_var2 = 'hello world!';
let my_var3 = 'hello world!';
</script>
If you use the above in the main page, you can not refer to either my_var2 or my_var3 in the iframe(s). You must use 'var' to accomplish that.
如果您在主页中使用上述内容,则不能在 iframe(s) 中引用 my_var2 或 my_var3。您必须使用“var”来完成此操作。
This is because "const, let, and class don't create properties on the global object".
这是因为“const、let 和 class 不会在全局对象上创建属性”。
SEE: What is the proper to write a global const in javascript es6?