在Iframe中设置变量

Lou*_*uis 3 javascript iframe namespaces window

是否可以使用iframe创建iframe document.createElement("iframe");,然后在iframe的窗口对象(如命名空间)中设置变量?

我尝试过这样的事情:

var Namespace = {}; 
var iframe = document.createElement("iframe"); 
iframe.src = "page.html"; 
document.body.appendChild(iframe);
var iwin = iframe.contentWindow || iframe.contentDocument.defaultView; 
iwin.Namespace = Namespace;
Run Code Online (Sandbox Code Playgroud)

但在page.html中我尝试登录Namespace并抛出一个未定义的错误.

Dag*_*bit 5

同源策略可能阻止您这样做.如果两个页面都使用file:// uri方案,则在某些浏览器中也会发生这种情况.

如果iframe和外部窗口将使用相同的域,一旦您的代码在服务器上,此问题就会消失.尝试使用apache从localhost提供服务进行检查,或者使用谷歌浏览器测试它,同时根据此帖子禁用同源策略:

在Chrome中停用相同的来源政策

另一方面,如果iframe需要位于不同的域,或者需要使用file:// uri方案,则需要使用某种解决方法.

将数据传递到另一个域的iframe的一种方法是通过iframe元素的src属性中的片段标识符,该属性将在iframe窗口的'location'对象的'hash'属性中可见; 例如:

外页:

<!doctype html>
<html><head></head><body>
<script>
  var Namespace = {foo:1, bar:2}; 
  var iframe = document.createElement("iframe"); 
  iframe.src = "frame.html#" + JSON.stringify(Namespace);
  document.body.appendChild(iframe);
</script>
</body></html>
Run Code Online (Sandbox Code Playgroud)

内页"frame.html":

<!doctype html>
<html><head></head><body>
<a href="#" onclick="alert(location.hash.substring(1))">click me</a>
</body></html>
Run Code Online (Sandbox Code Playgroud)