contentWindow.document.execCommand('print'

2020-03-30 05:25发布

问题:

I am implementing some print function for iframe now , and i am using below code:

 $('#printBtn').click(function(){
     var iframe = document.getElementById('previewInfoBodyFrame');
     iframe.contentWindow.document.execCommand('print', false, null);
     return false;     
}); 

but i found that in firefox browser, it's not working , but for IE,chrome and safari, it works fine. searched a lot but cannot figure out how this happening. anyone can give some ideas? Thanks

回答1:

execCommand('print') is not supported by Firefox.

https://developer.mozilla.org/en-US/docs/Web/API/document.execCommand

You can use the print() function instead.

window.print() ;

https://developer.mozilla.org/en-US/docs/Web/API/Window.print

You might want to read this: Printing a (part of) webpage with Javascript

Hope this helps.



回答2:

with the help of naota, i fixed this issue for firefox , here is my full solution for printing iframe content, working fine for me .

 $('#printBtn').click(function(){
    var iframe = document.getElementById('previewInfoBodyFrame');
    if(navigator.userAgent.toLowerCase().indexOf("firefox")!=-1){
         iframe.contentWindow.print();              
    }else{
         iframe.contentWindow.document.execCommand('print', false, null);
    }
    return false;     
 } ); 


标签: jquery iframe