简体   繁体   English

Google Chrome扩展程序:无法启动“打印”对话框

[英]Google Chrome Extension: Cannot launch Print dialog

I'd like to launch the print dialog on button click in my google chrome extension. 我想在我的Google chrome扩展程序中单击按钮后启动“打印”对话框。 The code seems to be working when the extension's html file is opened as a standalone file, but not when it's loaded as an extension. 当扩展程序的html文件作为独立文件打开时,该代码似乎有效,但当作为扩展程序加载时却无效。

HTML: <input id="print_page" type="button" value="Print" onclick="print_p()" /> HTML: <input id="print_page" type="button" value="Print" onclick="print_p()" />

JavaScript: function print_p(){ window.print();} JavaScript: function print_p(){ window.print();}

Any idea as to what's wrong? 有什么问题的主意吗?

Aside from the inline JavaScript problem that I mentioned as a duplicate, it seems that invoking the print dialog from a popup (or a background page) is impossible . 除了我提到的内联JavaScript问题外,似乎不可能从弹出窗口(或背景页面)调用打印对话框

A workaround would be to have a "print helper" page in your extension, that opens in a normal tab and can open a print dialog. 一种解决方法是在扩展程序中具有一个“打印帮助程序”页面,该页面在常规选项卡中打开并可以打开一个打印对话框。

A possible architecture: 可能的架构:

  1. On a click in a popup, data to print is being sent to the background page: 在弹出窗口中单击,将要打印的数据发送到后台页面:

     function printClick(){ chrome.runtime.sendMessage({ print: true, data: whateverYouWantToPrint }); } 

    It's routed through the background page so that you don't have to worry about popup closing. 它通过后台页面路由,因此您不必担心弹出窗口关闭。

  2. In the background page, a helper page is opened: 在后台页面中,将打开一个帮助页面:

     var printData; chrome.runtime.onMessage.addListener( function(request, sender, sendResponse){ if(request.print) { printData = request.data; chrome.tabs.create( { url: chrome.runtime.getURL("print.html") } ); } // ... }); 
  3. In the print helper page, a script print.js requests the data, formats it as required and invokes the print dialog: 在打印帮助器页面中,脚本print.js请求数据,根据需要设置其格式并调用打印对话框:

     chrome.runtime.sendMessage({ getPrintData: true }, function(response){ formatDataIntoPage(response.data); window.print(); }); 
  4. Back in the background page, serve the data on request from print helper: 返回后台页面,根据打印助手的要求提供数据:

     chrome.runtime.onMessage.addListener( function(request, sender, sendResponse){ // ... if(request.getPrintData) { sendResponse({ data: printData }); } }); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM