Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
254 views
in Technique[技术] by (71.8m points)

javascript - 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?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...