jquery - iframe access denied in IE on some pages

前端 未结 5 1451
深忆病人
深忆病人 2020-12-05 15:36

I\'m the author of printThis, a jquery plugin for printing.

https://github.com/jasonday/printThis

I have a user that has brought up an issue, that I have bee

5条回答
  •  星月不相逢
    2020-12-05 16:10

    Issue is due to IE not inheriting the parent document.domain.

    Unfortunately, once you get into this murky area, it took some specific hacks to get this to work properly.

    Basically doing a check for if document.domain is being explicitly set and the browser is IE.

    Full updated plugin:

    https://github.com/jasonday/printThis

    (function ($) {
        var opt;
        $.fn.printThis = function (options) {
            opt = $.extend({}, $.fn.printThis.defaults, options);
            var $element = this instanceof jQuery ? this : $(this);
    
                var strFrameName = "printThis-" + (new Date()).getTime();
    
                if(window.location.hostname !== document.domain && navigator.userAgent.match(/msie/i)){
                    // Ugly IE hacks due to IE not inheriting document.domain from parent
                    // checks if document.domain is set by comparing the host name against document.domain
                    var iframeSrc = "javascript:document.write(\"\")";
                    var printI= document.createElement('iframe');
                    printI.name = "printIframe";
                    printI.id = strFrameName;
                    printI.className = "MSIE";
                    document.body.appendChild(printI);
                    printI.src = iframeSrc;
    
                } else {
                     // other browsers inherit document.domain, and IE works if document.domain is not explicitly set
                    var $frame = $("