【问题标题】:Can I access contents of an iframe from a subdomain if I use www. on the main domain?如果我使用 www,我可以从子域访问 iframe 的内容吗?在主域上?
【发布时间】:2010-11-24 18:52:45
【问题描述】:

我正在尝试访问和编辑 iframe 的内容。 iframe 指向我自己域的子域上的页面。这是我正在使用的 javascript 代码,虽然它并不重要。

$('iframe').load(function(){
  $('div.code textarea.html').val($(this).contents()[0].html());
});

当我运行它时,它说我无权从 www.domain.com 访问 example.domain.com。那么我尝试访问的域是否具有 www 是否重要?因为我的主机不允许我不用www。

【问题讨论】:

    标签: javascript jquery iframe permissions


    【解决方案1】:

    Same-Origin-Policy 默认需要完全相同的主机名。

    告诉它不要,设置:

    document.domain= 'domain.com';
    

    来自父 (www.) 文档和 iframe(示例)文档中的脚本。

    请注意,从脚本设置静态写入 iframe(或图像)的加载是不可靠的,因为可以想象 iframe 可能会在解析器读取 iframe 标记和读取脚本之间完全加载设置 onload 的标签。

    为避免这种情况,要么将事件处理程序包含为内联的 '

    【讨论】:

    • 这样做是否可以让子域访问域的cookies?
    • 通过阅读“window.parent.document.cookie”,是的。但是,通过“domain”cookie 参数发送和接收 cookie 不受 document.domain 的影响。
    猜你喜欢
    • 2012-03-04
    • 1970-01-01
    • 2012-10-31
    • 1970-01-01
    • 2014-03-16
    • 2014-05-30
    • 2019-06-29
    • 1970-01-01
    • 2021-08-07
    相关资源
    最近更新 更多