Reputation: 13
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
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:
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") }
);
}
// ...
});
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 });
}
});
Upvotes: 4