Getting Undefined Error while printing iframe through Ctrl+P
I have a document which pops up on the site within a JQuery Modal Box. The document has a print button at the end which just prints the document in the Pop-Up Box.
I wanted to print the document, only within the iframe, through Ctrl+P. That required preventing default behavior of printing all the page including the background.
This is the JQuery Code for the printing:-
- $(document).keydown(function(event) {
- if ( ( (event.ctrlKey == true) || (event.metaKey == true) ) && (event.which == '80')) { //Ctrl+P or Cmd + P
- event.preventDefault();
- printAssessment();
- }
-
- });
-
- function printAssessment() {
- if ($('#frameContainer').length) {
- $('#lightboxFrame')[0].contentWindow.print();
- }
- }
The HTML for my page with the iframe is below:-
- <div id="frameContainer">
- <iframe id="lightboxFrame" width="950px" scrolling="auto" height="500px">
- <!DOCTYPE html>
- <html>
- <head>
- <body> (Whole Document in a Div) </body>
- ...
Now, the problem is that when I open up my modal box and press Ctrl+P, it prints if I don't scroll the modal, in the way I want it to be. But if I scroll the modal, and then press Ctrl+P, it gives me the following error:-
- Uncaught TypeError: Cannot read property 'contentWindow' of undefined
Strangely, even though when iframe is open, it still finds it undefined, but only when I scroll the modal iframe. If I just open the modal and press Ctrl+P, it prints fine.
Any help please?
Thanks.