I am printing a page containing google maps API v3 map from within an iframe. I implemented the following code to make sure the page has loaded fully before printing the iframe.
/**
* Auto print the page once the full document has finished loading
*/
function checkDocumentStateChange(documentElement) {
var document = documentElement;
console.log('Document ReadyState: ' + document.readyState);
document.onreadystatechange = function () {
console.log('Document ReadyState: ' + document.readyState);
if (document.readyState === 'complete') {
console.log("Document fully loaded!");
console.log("Printing report from within iframe");
setTimeout(function () {
window.print();
var requestOrigin = '@viewModel.RequestOrigin';
if(!!requestOrigin) {
// Tell the parent window that the print has occurred, so it can prepare to cleanup and remove this iframe
console.log("Send postMessage: secret");
parent.postMessage('secret', requestOrigin);
}
}, 500);
}
}
}
However, even with with a 500 millisecond delay AFTER document.readystate === 'complete'
is true, often times the page prints with a grey/blank google maps canvas, with no images.
If I hit window.print() again without reloading the page, then it prints the iframe with all map images as expected. So the document ready state is lying.
What can I do to solve this besides increasing the delay even longer (which I don't want to do as it punishes people to wait long when the content loads quickly)
The answer was simple, just use Google Maps event handler api. In my tests, it fires
bounds_changed
, thentilesloaded
and finallyidle
in that order. So I just set a flag to check for later into theidle
event and it works perfectly.