以编程方式访问使用数据URI作为源的iframe [英] Programmatically accessing an iframe that uses a data URI as a source

查看:224
本文介绍了以编程方式访问使用数据URI作为源的iframe的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用数据URI以编程方式创建iframe:

I'm creating an iframe programmatically using the "data" URI:

<iframe id="myFrame" src='data:text/html;charset=utf-8,<!DOCTYPE html><html><head></head><body><h1>Hello.</h1></body></html>'></iframe>​

此框架加载正常,但似乎以编程方式使用iframe命中跨域安全检查。

This frame loads fine, but it seems that working with the iframe programmatically hits cross-domain security checks.

var iframeDoc = document.getElementById('myFrame').contentWindow.document;
$(iframeDoc.body).find('h1').text('Changed');

在Chrome和Safari中引发错误:

Throws an error in Chrome and Safari:

不安全的JavaScript尝试使用URL访问框架
data:text / html; charset = utf-8,...来自带URL的框架http:// ... $ b请求访问的$ b帧具有'http'协议,访问
的帧具有协议''。协议必须匹配。

Unsafe JavaScript attempt to access frame with URL data:text/html;charset=utf-8,... from frame with URL http://... The frame requesting access has a protocol of 'http', the frame being accessed has a protocol of ''. Protocols must match.

这是一个显示安全错误的小提琴: http://jsfiddle.net/bhGcw/4/

Here's a fiddle showing the security error: http://jsfiddle.net/bhGcw/4/

Firefox和Opera不会抛出此异常并允许要更改的iframe内容。好像Webkit看到了数据URI的空白协议,并认为这是一个跨域违规。

Firefox and Opera do not throw this exception and allow the iframe contents to be changed. Seems like Webkit sees a blank protocol for data URIs, and sees this as a cross-domain violation.

有什么方法吗?

推荐答案

看来Webkit在域名检查代码

String DOMWindow::crossDomainAccessErrorMessage(DOMWindow* activeWindow)
{
    ...

    SecurityOrigin* activeOrigin = activeWindow->document()->securityOrigin();
    SecurityOrigin* targetOrigin = document()->securityOrigin();
    if (targetOrigin->protocol() != activeOrigin->protocol())
        return message + " The frame requesting access has a protocol of '" + activeOrigin->protocol() + "', the frame being accessed has a protocol of '" + targetOrigin->protocol() + "'. Protocols must match.\n";

    ...
}

看起来Chromium是比HTML5规范更严格,至少根据以下错误报告:

It looks like Chromium is being more strict than the HTML5 spec, at least according the following bug reports:

  • https://bugs.webkit.org/show_bug.cgi?id=17352
  • https://code.google.com/p/chromium/issues/detail?id=58999

Chromium devs似乎并不赞成放宽这条规则。糟糕。

Chromium devs don't seem to be in favor of relaxing this rule. Bummer.

这篇关于以编程方式访问使用数据URI作为源的iframe的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆