Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
235 views
Welcome To Ask or Share your Answers For Others

1 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...