print() not working on opera browser
I am trying to open a print dialog 开发者_运维知识库box in Opera browser using javascript.
The print()
is working fine in all browsers but in opera it doesn't work.
My print()
code as,
var printContent = document.getElementById(elementId);
var windowUrl = url;
var uniqueName = new Date();
var windowName = 'Print' + uniqueName.getTime();
var printWindow = window.open(windowUrl, windowName, 'scrollbars=yes');
printWindow.document.write(printContent.innerHTML);
printWindow.document.close();
printWindow.focus();
printWindow.print();
I want to open print dialog box in Opera browser. Can anyone help me?
In Opera, the print dialog will only display if the page has loaded (see the link in cjrh's comment), so maybe the window you're dynamically opening has not finished loading when you try to print it. Try replacing this line:
printWindow.print();
with this line:
printWindow.onload = printWindow.print;
I had the same problem and this was the only solution that actually worked for me:
window.addEventListener('load', function(e) { window.print(); }, false);
Version 11.60
Build 1185
Platform Win32
System Windows XP
I think there are two things happening here:
As others have pointed out, Opera requires that window.print() be triggered by an event: a click or a load event, for example. In general, you'll need to wrap window.print() in an event listener. Try
window.addEventListener('load', function(e) { window.print(); }, false);
orwindow.onload = function(){ window.print() }
It looks like Opera also only allows a limited subset of window methods on windows that are opened via JavaScript. print() doesn't appear to be one of the methods allowed.
I solved this issue via jQuery with this very simple function instead ofissue the print one which you can replace on your code and will satisfy your needs for Opera and the rest of the browsers.
$(document).ready(function(){
if($.browser.opera){
window.print();
}
else printWindow.print();
});
精彩评论