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

标签 javascript jquery google-chrome iframe

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

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

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

最佳答案

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

要解决此问题,如果您的 iframe 与父页面同源,您可以使用:

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

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

实际上,即使对于涉及 window.open() 的跨源框架,也有一个 hack,因此在没有“allow-popups”权限的情况下无法在沙盒 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();
  };
}

External Live Demo ,因为 open() 无法在 stack-snippet 的沙盒 iframe 中工作。

关于javascript - 如何从 iframe 中设置 Chrome 打印对话框的默认文件名?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42014507/

相关文章:

javascript - Ajax 只被调用一次

php - Ajax调用php函数

html - 为什么这个 SVG 滤镜动画在 Edge 或 Chrome 中不起作用?

javascript - 如何检测 Chrome(和其他)中是否启用了 native FlashBlock?

javascript - 如何向此按钮添加 CSS 动画?

javascript - Atom typescript 插件找不到名称 'describe'

javascript - 使用nodejs查询MongoDb

javascript - 如果在带有对话框的页面上找不到事件,则自动注销

jquery - 类更改后单击事件不起作用

html - 除了 chrome,页面在任何地方都能正确显示。?