【问题标题】:Google Chrome Extension: Cannot launch Print dialogGoogle Chrome 扩展程序:无法启动打印对话框
【发布时间】:2014-06-13 05:12:28
【问题描述】:

我想在我的 google chrome 扩展程序中单击按钮时启动打印对话框。当扩展程序的 html 文件作为独立文件打开时,代码似乎可以正常工作,但在作为扩展程序加载时却不行。

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

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

有什么问题吗?

【问题讨论】:

  • @Xan:我已经尝试过了,但结果对我没有帮助。我还尝试了一种不同的方法,它再次适用于独立的 html 文件而不是扩展名。这里是(抱歉格式化)HTML: JS: function print_p(){ window.print(); } $("#print_page").click(function() { print_p(); });
  • 你应该编辑你的问题而不是评论;此外,内联代码用反引号分隔,`。除非您将其包装在 $(document).ready({/*...*/}); 中,否则您的 jQuery 尝试仍然是错误的
  • @Xan:我会记住这一点。谢谢你的努力。但我也试过了。我开始怀疑是否不允许从 chrome 中的扩展程序访问打印对话框。
  • 我刚刚对其进行了测试,但它在弹出窗口中不起作用。在其他扩展页面上它可以工作。你的情况是这样吗?

标签: javascript google-chrome google-chrome-extension


【解决方案1】:

除了我提到的重复的内联 JavaScript 问题之外,似乎从弹出窗口(或背景页面)调用打印对话框是不可能的

一种解决方法是在您的扩展程序中添加一个“打印助手”页面,该页面在普通选项卡中打开并可以打开打印对话框。

一种可能的架构:

  1. 在弹出窗口中单击时,要打印的数据被发送到后台页面:

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

    它通过后台页面路由,因此您不必担心弹出窗口关闭。

  2. 在后台页面中,打开了一个帮助页面:

    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. 在打印帮助页面中,脚本print.js 请求数据,根据需要对其进行格式化并调用打印对话框:

    chrome.runtime.sendMessage({ getPrintData: true }, function(response){
      formatDataIntoPage(response.data);
      window.print();
    });
    
  4. 返回后台页面,根据打印助手的请求提供数据:

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

【讨论】:

    猜你喜欢
    • 2023-02-02
    • 1970-01-01
    • 2011-06-18
    • 1970-01-01
    • 1970-01-01
    • 2011-02-08
    • 2023-03-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多