user3727438
user3727438

Reputation: 13

Google Chrome Extension: Cannot launch Print dialog

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

Any idea as to what's wrong?

Upvotes: 1

Views: 2355

Answers (1)

Xan
Xan

Reputation: 77482

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

Upvotes: 4

Related Questions