Bomin Bomin - 3 months ago 14
Javascript Question

How to remove the iFrame DOM node that is used for printing

I'm creating a iFrame DOM dynamically only for printing. Here's my code doing the creation and show printing window.
var url, data, _iFrame, nonce, iframeId;

data = new Blob([buffer], {
type: 'application/pdf'
});
url = window.URL.createObjectURL(data);
_iFrame = document.createElement('iframe');
nonce = (new Date()).getTime();
var iframeId = "printPDF" + nonce;
_iFrame.id = iframeId
_iFrame.setAttribute('style', 'visibility:hidden;');
_iFrame.setAttribute('src', url);
document.body.appendChild(_iFrame);

$('#' + iframeId)[0].focus();
$('#' + iframeId)[0].contentWindow.print();


But the thing is, I need to remove the iFrame after the printing is done (either print or cancel). How can I get the event in javascript?

Answer

I actually resolved this on my own.

The first thing is not to hide the iframe. Instead, make it 0 size. style='height: 0;width: 0;'.

Then, bind the focus event of the iframe and remove the iframe when it's focused again after the print dialog gets dismissed.

Well, I tried the focus event, and I failed to get into it because the iframe was hidden.