2012-08-15 128 views
1

我使用此代码,其源于herehereJavascript/jQuery:删除iframe后contentWindow.print

$('#my_button').on('click', function (e) { 
    var iframe = document.createElement('iframe'); 
    iframe.id = "my_iframe"; 
    iframe.onload = function() { 
     var doc = iframe.contentDocument || iframe.contentWindow.document; 
     doc.getElementsByTagName('body')[0].innerHTML = "<p>test123</p>"; 

     iframe.contentWindow.focus(); 
     iframe.contentWindow.print(); 

     $("#my_iframe", top.document).remove(); 
    }; 

    document.getElementsByTagName('body')[0].appendChild(iframe); 
}); 

没有remove行,它打印罚款。但是,在有机会执行print()之前,remove行将删除iframe。我如何设置某种回调以便打印并仅删除iframe?

谢谢。

回答

4

我发现这个解决方案时,我正在寻找打印事件检测:

http://tjvantoll.com/2012/06/15/detecting-print-requests-with-javascript/

这里我想补充JS代码由Stano的要求,但它也可以参考整个链接后,因为是非常重要的这种方法的局限性。一般来说,这篇文章是关于仅适用于IE的onafterprint事件和一个解决方案,以使其他浏览器可以使用该事件。

(function() { 
    var beforePrint = function() { 
     console.log('Functionality to run before printing.'); 
    }; 
    var afterPrint = function() { 
     console.log('Functionality to run after printing'); 
    }; 

    if (window.matchMedia) { 
     var mediaQueryList = window.matchMedia('print'); 
     mediaQueryList.addListener(function(mql) { 
      if (mql.matches) { 
       beforePrint(); 
      } else { 
       afterPrint(); 
      } 
     }); 
    } 

    window.onbeforeprint = beforePrint; 
    window.onafterprint = afterPrint; 
}()); 
+0

Upvoted,但也请复制粘贴+ window.onafterprint'代码从链接到您的答案。另外提到它在所有浏览器中都不支持。 – Stano 2012-08-15 08:47:48

+0

完成 - 但阅读链接的文章以了解限制很重要。 – m7o 2012-08-15 08:55:17

+0

感谢:) – Nick 2012-08-15 12:08:00

2

创建这样一个功能:

function printIframe(iframe,callback) { 
    iframe.contentWindow.print(); 
    if (callback && typeof(callback) === "function") { 
    // execute the callback, passing parameters as necessary 
    callback(); 
    } 
} 

,并调用它,而不是像这样其他两个功能。 printIframe(iframe,function(){$(“#my_iframe”,top.document).remove();})

如果你喜欢,你也可以延迟使用setTimeout。

setTimeout(function() {alert('hello');},1250); 
+0

这是一个很好的回调,我已经+1,但它并没有真正检查,看看打印完成。你只需要相信这是在延迟结束的时候完成的(当然可能会这样做)。 – Nick 2012-08-15 12:11:43

+0

是的,这是真的尼克。结合m7os解决方案,您可以获得更好的解决方案。 – 2012-08-15 12:15:26

+0

但是,我注意到,至少有一个jQuery插件使用你的setTimeout方法来摆脱iframe,所以你是在好公司:) – Nick 2012-08-15 22:47:24