Google Chrome 扩展程序:无法启动打印对话框 [英] Google Chrome Extension: Cannot launch Print dialog

查看:22
本文介绍了Google Chrome 扩展程序:无法启动打印对话框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'd like to launch the print dialog on button click in my google chrome extension. 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:<input id="print_page" type="button" value="Print" onclick="print_p()"/>

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

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

知道出了什么问题吗?

推荐答案

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

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.

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

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.

一种可能的架构:

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

  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.

在后台页面,打开了一个辅助页面:

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") }
    );
  }
  // ...
});

  • 在打印帮助页面中,脚本 print.js 请求数据,根据需要对其进行格式化并调用打印对话框:

  • In the print helper page, a script print.js requests the data, formats it as required and invokes the print dialog:

    chrome.runtime.sendMessage({ getPrintData: true }, function(response){
      formatDataIntoPage(response.data);
      window.print();
    });
    

  • 返回后台页面,根据打印助手的请求提供数据:

  • 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 });
      }
    });
    

  • 这篇关于Google Chrome 扩展程序:无法启动打印对话框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆