我正在以编程方式使用"data“URI创建一个iframe:
<iframe id="myFrame" src='data:text/html;charset=utf-8,<!DOCTYPE html><html><head></head><body><h1>Hello.</h1></body></html>'></iframe>此框架加载良好,但使用iframe编程似乎会执行跨域安全检查。
var iframeDoc = document.getElementById('myFrame').contentWindow.document;
$(iframeDoc.body).find('h1').text('Changed');在Chrome和Safari中引发一个错误:
不安全的JavaScript试图用URL数据访问帧:text/html;charset=utf-8,.从框架与URL http://..。请求访问的帧具有'http‘协议,被访问的帧具有’协议‘。协议必须匹配。
下面是一个显示安全错误的小提琴:http://jsfiddle.net/bhGcw/4/
Firefox和Opera不抛出此异常,并允许更改iframe内容。似乎Webkit看到了数据URI的空白协议,并且认为这是跨域的违规行为。
有办法绕过这件事吗?
发布于 2013-01-04 00:52:30
似乎Webkit在他们的domain checking code中做了一个简单的字符串比较。
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";
...
}看起来铬比HTML5规范更严格,至少根据以下的bug报告:
铬代似乎不赞成放松这一规则。真扫兴。
发布于 2014-03-30 19:21:54
现在有点晚了,不如使用HTML5属性srcdoc,而不是使用数据URL。
<iframe id="iframe" srcdoc='<html><body><h1>Hello!</h1></body></html>'></iframe>
<script type="text/javascript">
$(function(){
$($("iframe")[0].contentWindow.document).find("h1").text("Modified from the parent window!");
});
</script>在http://jsfiddle.net/ff3bF/有一个例子
发布于 2014-09-08 04:11:21
@jamie提出的答案对于将HTML加载到iframe并允许随后与内容文档进行编程交互非常有效。
XHTML并不是那么容易。
srcdoc属性似乎仅限于HTML,而不是XHTML。
所做的工作是使用Blob URL,该URL允许指定content-type。
var documentSource = '<?xml version="1.0" encoding="UTF-8"?>\n<html xmlns="http://www.w3.org/1999/xhtml">\n<head>...';
var blob = new Blob([documentSource], { type: "application/xhtml+xml" });
iframe.src = URL.createObjectURL(blob);这种技术至少适用于Chrome、Firefox和Safari。
https://stackoverflow.com/questions/14149523
复制相似问题