0

I am trying to print directly from a url which is a src of an iframe

<iframe id="pagetwo" src="https://78.media.tumblr.com/b90ee054017d4ddd25a4c4161127c7d4/tumblr_p8iyzdMhuZ1qzooxpo1_1280.jpg" width="550" height="700"></iframe>

<a id="downloadlink2" class="link_print" href="" target="_blank"  onclick="printDocument('pagetwo')">
  <img src="assets/print-button.png" alt="">
</a>

While printing this script:

function printDocument(iframe) {
  console.log(window.frames);
  var iframe = document.getElementById(iframe);
  if (iframe.src) {
    var frm = iframe.contentWindow;
    frm.focus();// focus on contentWindow is needed on some versions  
    frm.print();
  }     
}

I am getting this error:

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

However when I am putting image in local, then it is working perfect

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
Atul Verma
  • 361
  • 8
  • 22
  • Possible duplicate: https://stackoverflow.com/questions/25098021/securityerror-blocked-a-frame-with-origin-from-accessing-a-cross-origin-frame – peeebeee May 11 '18 at 07:41

1 Answers1

0

The main issue is indeed the same as the one described in SecurityError: Blocked a frame with origin from accessing a cross-origin frame, but you have a special use-case that may warrant its own answer.

Since what you are doing is to load this cross-origin frame only to print the image it points to, you can create yourself the document which will display this image in a same-origin way, and call print on this same-origin frame:

In normal cases, you could just create a Blob of such a document and display it in your frame:

var frame = document.createElement('iframe');
var external_doc = new Blob(['<html><body><img src="https://78.media.tumblr.com/b90ee054017d4ddd25a4c4161127c7d4/tumblr_p8iyzdMhuZ1qzooxpo1_1280.jpg"></body></html>'], {
  type: 'text/html'
});
frame.onload = function() {
  try {
    this.contentWindow && this.contentWindow.print();
    return;
  } catch (e) {}
  console.error('in a protective iframe?');
};
frame.src = URL.createObjectURL(external_doc);
document.body.appendChild(frame);

But since StackSnippet's are themselves ran in over-protective iframes, this won't work here, but it will in jsfiddle.

Ps: If you need to support older browsers that didn't supported the Blob API, you could also just append an <img> from an about:blank iframe: jsfiddle

Kaiido
  • 123,334
  • 13
  • 219
  • 285