-1

我正在从 iframe 中打印包含 google maps 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);

     }
  }

}

document.readystate === 'complete'然而,即使 AFTER确实有 500 毫秒的延迟,页面通常也会使用灰色/空白的谷歌地图画布打印,没有图像。

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

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

4

1 回答 1

0

答案很简单,只需使用 Google Maps 事件处理程序 api。在我的测试中,它会触发bounds_changed,然后tilesloadedidle顺序触发。所以我只是设置了一个标志以便稍后检查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);
      });
于 2017-05-24T20:03:26.353 回答