Blocked a frame with origin “http://localhost:8084” from accessing a cross-origin frame

一笑奈何 提交于 2019-12-19 07:54:18

问题


I'm trying to print a pdf generated by jspdf and loaded on iframe, but I'm getting that error message:

"DOMException: Blocked a frame with origin "http://localhost:8084" from accessing a cross-origin frame."

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();
    });
}

回答1:


DOMException: Blocked a frame with origin "http://localhost:8084" from accessing a cross-origin frame."

This message is valid because when you load iframe with the pdf you set the src attribute with a datauristring, not a 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))

The policy is violated using your approach because the protocols (http/data) are different:

  • one is http://localhost:8084
  • the iframe is: data:application/pdf

Another mistake is:

document.getElementById('pdf-box')

You must use the id and not the name, so change it to:

document.getElementById('pdf-prueba')

The following changed code works in 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>


来源:https://stackoverflow.com/questions/42100205/blocked-a-frame-with-origin-http-localhost8084-from-accessing-a-cross-origi

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!