window.print()onLoad

时间:2016-12-14 01:42:37

标签: javascript

我正在尝试在页面加载时打开打印对话框。使用下面的代码,我没有出现任何错误,窗口打开,但onload似乎永远不会打开,打印对话框也没有打开(Firefox和Chrome - 没有测试过其他浏览器)。

我试过这些:

var printWindow = window.open(result.url);

printWindow.window.onload = function () {
    printWindow.window.print();
    console.log("Printing page");
}

var printWindow = window.open(result.url);

printWindow.onload = function () {
    printWindow.print();
    console.log("Printing page");
}

var printWindow = window.open(result.url);
printWindow.addEventListener("load", function() {
    printWindow.print();
    console.log("Got here");
});

result.url的示例:

http://ourserver/arcgis/rest/directories/arcgisoutput/OurTools/Print_Tool_Adv_GPServer/_ags_WebMap_de458080-c19a-11e6-8ade-005056a65a05.PDF

我正在试着看看这个post是否适用于我的情况,以及我如何能够将答案用于我的优势。我允许用户生成新网址的原始窗口位于http://ourserver/ourapp,而新网址位于http://ourerver/arcgis/ ... 我不相信这是相同的情况,但我试图看看如果是这种情况,如何利用建议的副本的答案。

更新 所以我终于使用postMessage方法获取了信号。但是,我认为我遇到了window.print()特定的问题,因为print语句出现在控制台上,但我仍然有以下问题:

  • 在Chrome上,不会打开打印对话框
  • 在Firefox上,打印对话框打开,但它打印出来:空白,而不是我打开窗口的网址...似乎页面在对话框打开之前没有完全加载或者某些东西(当我在没有处理程序的情况下直接调用printWindow.print()时会发生同样的事情。

      var printWindow = window.open(result.url);
    
      var eventMethod = window.addEventListener ? "addEventListener" : "attachEvent";
      var eventer = window[eventMethod];
      var messageEvent = eventMethod == "attachEvent" ? "onmessage" : "message";
    
      // Listen to message from child window
      eventer(messageEvent,function(e) {
        console.log('origin: ', e.origin)
    
      // Check if origin is proper
      if( e.origin != 'http://ourserver' ){ return }
        console.log('parent received message!: ', e.data);
    
        try {
          //attempt to deserialize function and execute as closure
          eval('(' + decodeURI(e.data) + ')();');
        } catch(e) {}
      }, false);
    
      printWindow.opener.postMessage({serializeFunction(openPrintDialog)}, 'http://ourserver');
    

代码引用了这些函数:

  function serializeFunction(f) {
    return encodeURI(f.toString());
  }

  function openPrintDialog() {
    printWindow.print();
    console.log("Got here");
  }

0 个答案:

没有答案
相关问题