Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I set the default filename for the Chrome print dialog from within an iframe?

I'm working on a project where my part of the project is a dashboard within an iframe. I have a request to make just the iframe I'm working on exportable as a PDF (that is, only show the iframe contents and not the wrapper stuff around it). I've gotten that to work using some jQuery, but I'm now stumped at setting a default filename for saving as PDF. This SO answer was helpful (setting document.title works when the page is not in an iframe), but it doesn't work when the export button is clicked when it is in the iframe view. Here's an example of what I've tried:

$('#export-button').click(function() {
    $('#iframe-contents').show();
    document.title = 'default_filename';
    window.print();
});

Does anyone know how to set the default filename in the Chrome print dialog when calling on window.print() from within an iframe?

like image 450
mgig Avatar asked Feb 02 '17 23:02

mgig


1 Answers

Firefox does set the pdf name directly to the iframe's document's name, weird that chrome doesn't.

For a workaround, if your iframe shares the same origin as your parent page, you can use :

document.title = window.parent.document.title = "yourTitle";

If they don't share the same origin, you're stuck.

Actually there is an hack, even for cross-origin frames involving window.open(), hence not working in sand-boxed iframes without 'allow-popups' permission.

function renameIframedPrint(title) {
  var title = "myFile";
  try {
    // same-origin frame
    document.title = window.parent.document.title = title;
    print();
  } catch (e) { // cross-origin frame

    // we could instead grab the current content of the page
    // but for the demo, location.href will do
    var p = window.open(location.href);
    p.onload = function() {
      // no more frame so we don't care ;-)
      p.document.title = "myFile";
      // a bit more hack to close the popup once printed...
      function closePopup() {
        p.close();
      }
      if ('onafterprint' in p) {
        // FF and IE
        p.onafterprint = closePopup
      } else {
        // webkit don't support onafterprint
        var mediaQueryList = p.matchMedia('print');
        mediaQueryList.addListener(mqlListener);

        function mqlListener(mql) {
          if (!mql.matches) {
            closePopup();
            mediaQueryList.removeListener(mqlListener);
          }
        }
      }
    }
    // we're ready
    p.print();
  };
}

External Live Demo, since open() won't work in stack-snippet's sand-boxed iframe.

like image 146
Kaiido Avatar answered Oct 05 '22 04:10

Kaiido