Document.readystate正在谎报正在加载的谷歌地图画布图像



我正在从iframe中打印一个包含谷歌地图API v3地图的页面。我实现了以下代码,以确保页面在打印 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);
}
}

}

但是,即使有 500 毫秒的延迟 AFTERdocument.readystate === 'complete'是真的,页面通常使用灰色/空白的谷歌地图画布打印,没有图像。

如果我再次点击 window.print() 而不重新加载页面,那么它会按预期打印包含所有地图图像的 iframe。因此,文档就绪状态是撒谎。

除了延长延迟之外,我还能做些什么来解决这个问题(我不想这样做,因为它会惩罚人们在内容快速加载时等待很长时间)

答案很简单,只需使用Google Maps事件处理程序api即可。在我的测试中,它触发bounds_changed,然后tilesloaded,最后按该顺序idle。所以我只是设置了一个标志,稍后在idle事件中检查,它工作得很好。

// this callback runs when the mapobject is created and rendered (because bound_changed fires at initialization), only fire it once to prevent unnecessary callbacks during panning/zooming
google.maps.event.addListenerOnce(map, 'bounds_changed', function () {
// do something only the first time the map is loaded
console.log("Google Maps event: bounds_changed");
});
// this callback runs when the mapobject is shown for the first time and all tiles are loaded
google.maps.event.addListener(map, 'tilesloaded', function () {
console.log("Google Maps event: tilesloaded");
});
// this callback runs when the mapobject is fully created and rendered and the map is completely idle
google.maps.event.addListener(map, 'idle', function () {
// do something only the first time the map is loaded
console.log("Google Maps event: idle");
mapReadyToPrint = true;
console.log("mapReadyToPrint:", mapReadyToPrint);
});

相关内容

  • 没有找到相关文章

最新更新