javascript iframe 中的 getElementById
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5022464/
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
getElementById within iframe
提问by webmaster alex l
Q: I have an iframe calling page X, on page X is a div w/ id=test. The value of this test div is "bubbles". On the parent page I need to read the value of the div and store it as a javascript var.
问:我有一个 iframe 调用页面 X,在页面 X 上是一个带有 div 的 div id=test。这个测试 div 的值是“气泡”。在父页面上,我需要读取 div 的值并将其存储为 javascript var。
Outcome: on the parent page have a document.write(iframedivvalue);output that will = whatever the value of the div inside the iframe.
结果:在父页面上有一个document.write(iframedivvalue);输出,该输出将 = iframe 内 div 的任何值。
Note:
笔记:
- as of right now page X is on a different domain.
- I am NOT trying to set anything inside the iframe, just read a divs value.
- 截至目前,第 X 页位于不同的域中。
- 我不想在 iframe 内设置任何东西,只是读取一个 divs 值。
采纳答案by Alex
You will still be blocked by the same-origin policy if the domains mismatch. Doesn't matter if you're just trying to grab a value.
如果域不匹配,您仍将被同源策略阻止。如果您只是想获取一个值,这并不重要。
回答by Meetai.com
As Alex says on the comment above, you will still be blocked by the JavaScript 'same-origin' policy.
正如 Alex 在上面的评论中所说的那样,您仍然会被 JavaScript 的“同源”政策阻止。
If your iframe is on the same domain, then you could try this:
如果您的 iframe 在同一个域中,那么您可以尝试以下操作:
document.getElementById('iframe-id').contentDocument.getElementById('canvas');
回答by Brad Christie
Assuming the iFrame has an assigned ID:
假设 iFrame 具有分配的 ID:
var iframe_div = document.getElementById('iframeid').document.getElementById('mydiv');
var content = iframe_div.innerHTML;
I believeshould work.
我相信应该工作。

