Google Chrome Extension: Cannot launch Print dialog

前端 未结 1 1373
误落风尘
误落风尘 2020-12-07 05:32

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 fi

相关标签:
1条回答
  • 2020-12-07 06:15

    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.

    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:

      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 });
        }
      });
      
    0 讨论(0)
提交回复
热议问题