如何从 iframe 中设置 Chrome 打印对话框的默认文件名?

mgi*_*gig 8 javascript iframe jquery google-chrome

我正在处理一个项目,其中我的项目部分是 iframe 中的仪表板。我有一个请求,将我正在处理的 iframe 制作为可导出为 PDF(也就是说,只显示 iframe 内容,而不显示它周围的包装器内容)。我已经使用一些 jQuery 让它工作了,但我现在很难设置一个默认的文件名来保存为 PDF。这个 SO 答案很有帮助(当页面不在iframe 中时设置 document.title 有效),但是当它在 iframe 视图中时单击导出按钮时它不起作用。这是我尝试过的示例:

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

有谁知道window.print()从 iframe 中调用时如何在 Chrome 打印对话框中设置默认文件名?

Kai*_*ido 5

Firefox 确实将 pdf 名称直接设置为 iframe 文档的名称,奇怪的是 chrome 却没有。

对于解决方法,如果您的 iframe 与父页面共享相同的源,您可以使用:

document.title = window.parent.document.title = "yourTitle";
Run Code Online (Sandbox Code Playgroud)

如果它们不具有相同的起源,那么您就会陷入困境

实际上,即使对于涉及 的跨源框架,也有一个 hack window.open(),因此在没有“允许弹出窗口”许可的情况下无法在沙盒 iframe 中工作。

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();
  };
}
Run Code Online (Sandbox Code Playgroud)

外部实时演示,因为open()无法在 stack-snippet 的沙盒 iframe 中工作。