Javascript 阻止了一个源为“http://localhost:8084”的框架访问跨源框架
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/42100205/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Blocked a frame with origin "http://localhost:8084" from accessing a cross-origin frame
提问by Malarkey86
I'm trying to print a pdf generated by jspdf and loaded on iframe, but I'm getting that error message:
我正在尝试打印由 jspdf 生成并加载到 iframe 上的 pdf,但我收到该错误消息:
"DOMException: Blocked a frame with origin "http://localhost:8084" from accessing a cross-origin frame."
“DOMException:阻止了一个具有“ http://localhost:8084”源的框架访问跨源框架。”
this is my code:
这是我的代码:
<iframe id="pdf-prueba" name="pdf-box"></iframe>
function open(){
var pdf = new jsPDF('p', 'mm', [55, 5]);
var data = pdf.output('datauristring');
$('#pdf-box').attr("src", data).load(function(){
document.getElementById('pdf-box').contentWindow.print();
});
}
回答by gaetanoM
DOMException: Blocked a frame with origin "http://localhost:8084" from accessing a cross-origin frame."
DOMException: 阻止了源为“ http://localhost:8084”的框架访问跨源框架。
This message is valid because when you load iframe with the pdf you set the src attribute with a datauristring, not a blob.
此消息是有效的,因为当您使用 pdf 加载 iframe 时,您将 src 属性设置为 datauristring,而不是 blob。
A simple solution is based on:
一个简单的解决方案基于:
- create a blob from pdf (i.e.: pdf.output('blob')..)
- convert the blob to URL (i.e.: URL.createObjectURL(blobPDF))
- 从 pdf 创建一个 blob(即:pdf.output('blob')..)
- 将 blob 转换为 URL(即:URL.createObjectURL(blobPDF))
The policy is violated using your approach because the protocols (http/data) are different:
使用您的方法违反了策略,因为协议 (http/data) 不同:
- one is http://localhost:8084
- the iframe is: data:application/pdf
- 一个是http://localhost:8084
- iframe 是:数据:应用程序/pdf
Another mistake is:
另一个错误是:
document.getElementById('pdf-box')
You must use the id and not the name, so change it to:
您必须使用 id 而不是名称,因此将其更改为:
document.getElementById('pdf-prueba')
The following changed code works in Chrome:
以下更改后的代码适用于 Chrome:
function open(){
var pdf = new jsPDF('p', 'mm', [55, 5]);
var blobPDF = pdf.output('blob');
var blobUrl = URL.createObjectURL(blobPDF);
$('#pdf-prueba').attr("src", blobUrl).load(function(e){
document.getElementById('pdf-prueba').contentWindow.print();
});
}
<iframe id="pdf-prueba" name="pdf-box"></iframe>

