Javascript 从父页面访问子 iFrame DOM

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5181911/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 16:01:09  来源:igfitidea点击:

Access child iFrame DOM from parent page

javascriptiframesame-origin-policy

提问by timelf123

Here is the deal:

这是交易:

domain.com/page -- Parent page (document.domain=domain.com) contains an iframe sub.domain.com/page -- Child iframe (document.domain=not set) is on a subdomain

domain.com/page -- 父页面 (document.domain=domain.com) 包含 iframe sub.domain.com/page -- 子 iframe (document.domain=not set) 在子域上

Is there any way to access the DOM of that iframe or am I out of luck?

有什么方法可以访问该 iframe 的 DOM 还是我不走运?

Does same origin policy block me from forcing a document.domain on an iframe contained within a parent page? I suppose that would defeat the purpose of the same origin policy... If that is the case, is there any workaround to access the DOM of the iframe on the rendered parent page?

同源策略是否阻止我在父页面中包含的 iframe 上强制使用 document.domain?我想这会破坏同源策略的目的......如果是这种情况,是否有任何解决方法来访问呈现的父页面上的 iframe 的 DOM?

回答by Zoidberg

There is a way. When the page in the iframe loads, have it do the following

有一种方法。当 iframe 中的页面加载时,让它执行以下操作

parent.childGetElementById = function (id) {return document.getElementById(id);}
parent.childLoaded();

This will make a function in the global scope of the parent page (that contains the iframe). Then in the parent, just have the following

这将在父页面(包含 iframe)的全局范围内创建一个函数。然后在父级中,只需具有以下内容

function childLoaded() {var dom = childGetElementById('someid');}

This is along as you have control of the page your loading into the iframe... if you do not, you are out of luck.

这是因为您可以控制加载到 iframe 中的页面......如果你不这样做,那你就不走运了。

回答by Gats

This is a browser security measure, otherwise everybody would be wrapping your banking websites and skimming off your passwords when you logged in.

这是一种浏览器安全措施,否则每个人都会在您登录时包装您的银行网站并窃取您的密码。

You can talk from the iframe to the parent, but not back into an iframe again.

您可以从 iframe 与父级对话,但不能再次返回 iframe。

回答by Marcus Fr?din

You're out of luck, as far as I know. You can talk between them using the hash-bang in the URL though, see thisfor a decent discussion.

据我所知,你运气不好。不过,您可以使用 URL 中的 hash-bang 在它们之间进行交谈,请参阅以进行体面的讨论。