Skip to main content
 首页 » 编程设计

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

2026年07月28日11虾米哥

我正在开发一个项目,我的部分项目是 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 中工作。