这是交易:
domain.com/page -- 父页面 (document.domain=domain.com) 包含一个 iframe
sub.domain.com/page -- 子 iframe (document.domain=not set) 在子域上
有什么方法可以访问该 iframe 的 DOM,还是我不走运?
同源策略是否阻止我在父页面中包含的 iframe 上强制使用 document.domain?我想这会破坏同源策略的目的......如果是这种情况,是否有任何解决方法可以访问呈现的父页面上的 iframe 的 DOM?
最佳答案
有一种方法。当 iframe 中的页面加载时,让它执行以下操作
parent.childGetElementById = function (id) {return document.getElementById(id);}
parent.childLoaded();
这将在父页面(包含 iframe)的全局范围内创建一个函数。然后在 parent 中,只有以下
function childLoaded() {var dom = childGetElementById('someid');}
这与您可以控制加载到 iframe 中的页面一样...如果您不这样做,那么您就不走运了。
关于javascript - 从父页面访问子 iFrame DOM,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5181911/