【问题标题】:Set a variable in an Iframe在 iframe 中设置变量
【发布时间】:2010-07-05 04:43:26
【问题描述】:

是否可以使用document.createElement("iframe"); 创建一个 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;

但在 page.html 中,我尝试记录 Namespace 并引发未定义的错误。

【问题讨论】:

    标签: javascript iframe window namespaces


    【解决方案1】:

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

    如果 iframe 和外部窗口将使用同一个域,那么一旦您的代码在服务器上,这个问题就会消失。尝试使用 apache 从 localhost 提供服务来检查,或者使用 google chrome 进行测试,并根据这篇文章禁用同源策略:

    Disable same origin policy in 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>
    

    内页“frame.html”:

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

    【讨论】:

    • 我的英雄;非常感谢你。不知道应用于 file:// 的相同来源
    【解决方案2】:

    document.appendChild(iframe);

    我很确定您需要将您创建的节点添加到 DOM。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-10-22
      • 1970-01-01
      • 2020-12-03
      • 2013-12-01
      • 2012-03-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多