2012-11-24 37 views
2

Firefox 16/17追加到动态iframe- jQuery - 在Firefox中不工作

以下代码是我写的用于打印元素的jquery插件。

这是在Firefox中工作,但它现在只显示一个空白页面,头部和身体都保持空白。这适用于Chrome浏览器的IE &。

github上: https://github.com/jasonday/jquery.printThis

演示: http://jsfiddle.net/jasonday/Tx4Uv/12/

代码:

(function($) { 
    var opt; 

    $.fn.printThis = function (options) { 
     opt = $.extend({}, $.fn.printThis.defaults, options); 

     var $element = (this instanceof jQuery) ? this : $(this); 

    // if Opera, open a new tab 
     if ($.browser.opera) 
     { 
      var tab = window.open("","Print Preview"); 
      tab.document.open(); 

      var doc = tab.document; 
     } 
    // add dynamic iframe to DOM 
     else 
     { 
     var strFrameName = ("printThis-" + (new Date()).getTime()); 

      var $iframe = $("<iframe id='" + strFrameName +"' src='about:blank'/>"); 

      if (!opt.debug) { $iframe.css({ position: "absolute", width: "0px", height: "0px", left: "-600px", top: "-600px" }); } 

      $iframe.appendTo("body"); 

      var $doc = $("#" + strFrameName).contents(); 
     } 
    // allow iframe to fully render before action 
    setTimeout (function() { 

     // import page css 
     if (opt.importCSS) 
     { 
       $("link[rel=stylesheet]").each(function(){ 
       var href = $(this).attr('href'); 
       if(href){ 
         var media = $(this).attr('media') || 'all'; 
         $doc.find("head").append("<link type='text/css' rel='stylesheet' href='" + href + "' media='"+media+"'>"); 
        } 
     }); 
     } 

     // add another stylesheet 
     if (opt.loadCSS) 
     { 
     $doc.find("head").append("<link type='text/css' rel='stylesheet' href='" + opt.loadCSS + "'>"); 

     } 

     //grab outer container 
     if (opt.printContainer) { $doc.find("body").append($element.outer()); } 
     else { $element.each(function() { $doc.find("body").append($(this).html()); }); } 

     //$doc.close(); 
     // print 
     ($.browser.opera ? tab : $iframe[0].contentWindow).focus(); 
     setTimeout(function() { ($.browser.opera ? tab : $iframe[0].contentWindow).print(); if (tab) { tab.close(); } }, 1000); 

     //removed iframe after 60 seconds 
     setTimeout(
     function(){ 
     $iframe.remove(); 
     }, 
     (60 * 1000) 
     ); 
    }, 333); 
    } 


    $.fn.printThis.defaults = { 
     debug: false, //show the iframe for debugging 
     importCSS: true, // import page CSS 
     printContainer: true, // grab outer container as well as the contents of the selector 
     loadCSS: "" //path to additional css file 
    }; 


    jQuery.fn.outer = function() { 
     return $($('<div></div>').html(this.clone())).html(); 
    } 
})(jQuery); 

回答

1

修复已经实施。

$doc移至setTimeout function内解决问题。

setTimeout (function() { 

     if ($.browser.opera) 
      { 
     var $doc = tab.document; 
     } else 
     { 
     var $doc = $("#" + strFrameName).contents(); 
     } 
... 

代码也在github上更新了。