Buttons Print Chrome problem

Buttons Print Chrome problem

jvcunhajvcunha Posts: 81Questions: 10Answers: 1

Hi,
in Chrome (Version 61.0.3163.100 (Official Version) 64 bit), it opens new tab but does not display the print preview, even setting autoPrint: true
Firefox, Safari, Edge and IE are ok apparently.
In this example the same problem occurs when you click Print, open the tab, and display the print preview. After closing the preview and clicking Print again, open the tab but not the preview .: https://datatables.net/extensions/buttons/examples/initialisation/export

Replies

  • allanallan Posts: 61,722Questions: 1Answers: 10,108 Site admin

    Thanks for posting this. There are a couple of other threads on this topic as well, including this one.

    It looks like an error that was introduced in Chrome 61.

    Allan

  • jvcunhajvcunha Posts: 81Questions: 10Answers: 1
    edited October 2017

    Hi Allan,
        Thanks for the quick response. Actually the solution you suggested worked. I commented on setTimeOut and it worked perfectly again.
        Once again, congratulations on the excellent component!
    It sure makes life easier for many developers.
    By marking as answered please!
    Regards,

    Jone

  • jvcunhajvcunha Posts: 81Questions: 10Answers: 1

    I was warned now that it works but ... lost all css :(
    sorry

  • jvcunhajvcunha Posts: 81Questions: 10Answers: 1

    curiosity:
       - if you leave Settimeout it opens the new tab but does not open the print preview;
       - if you click on any other chrome tab and then go back to this where the report is mounted, the preview appears ... ie changing the tab and returning it appears!
       hope this can help in a solution

  • jvcunhajvcunha Posts: 81Questions: 10Answers: 1

    Hi Allan,
        I changed the code of buttons.print.js not to open another tab but to inject a frame into the current page. After that it opens the direct preview on the page without pruning of the new tab, this way the chrome problem does not occur and maintains the css.
        I hope you can help other users, work for me.
    Here is updated code:

    (function( factory ){
        if ( typeof define === 'function' && define.amd ) {
            // AMD
            define( ['jquery', 'datatables.net', 'datatables.net-buttons'], function ( $ ) {
                return factory( $, window, document );
            } );
        }
        else if ( typeof exports === 'object' ) {
            // CommonJS
            module.exports = function (root, $) {
                if ( ! root ) {
                    root = window;
                }
    
                if ( ! $ || ! $.fn.dataTable ) {
                    $ = require('datatables.net')(root, $).$;
                }
    
                if ( ! $.fn.dataTable.Buttons ) {
                    require('datatables.net-buttons')(root, $);
                }
    
                return factory( $, root, root.document );
            };
        }
        else {
            // Browser
            factory( jQuery, window, document );
        }
    }(function( $, window, document, undefined ) {
    'use strict';
    var DataTable = $.fn.dataTable;
    
    
    var _link = document.createElement( 'a' );
    
    /**
     * Convert a `link` tag's URL from a relative to an absolute address so it will
     * work correctly in the popup window which has no base URL.
     *
     * @param  {node}     el Element to convert
     */
    var _relToAbs = function( el ) {
        var url;
        var clone = $(el).clone()[0];
        var linkHost;
    
        if ( clone.nodeName.toLowerCase() === 'link' ) {
            _link.href = clone.href;
            linkHost = _link.host;
    
            // IE doesn't have a trailing slash on the host
            // Chrome has it on the pathname
            if ( linkHost.indexOf('/') === -1 && _link.pathname.indexOf('/') !== 0) {
                linkHost += '/';
            }
    
            clone.href = _link.protocol+"//"+linkHost+_link.pathname+_link.search;
        }
    
        return clone.outerHTML;
    };
    
    
    DataTable.ext.buttons.print = {
        className: 'buttons-print',
    
        text: function ( dt ) {
            return dt.i18n( 'buttons.print', 'Print' );
        },
    
        action: function ( e, dt, button, config ) {
            var data = dt.buttons.exportData( config.exportOptions );
            var addRow = function ( d, tag ) {
                var str = '<tr>';
    
                for ( var i=0, ien=d.length ; i<ien ; i++ ) {
                    str += '<'+tag+'>'+d[i]+'</'+tag+'>';
                }
    
                return str + '</tr>';
            };
    
            // Construct a table for printing
            var html = '<table class="'+dt.table().node().className+'">';
    
            if ( config.header ) {
                html += '<thead>'+ addRow( data.header, 'th' ) +'</thead>';
            }
    
            html += '<tbody>';
            for ( var i=0, ien=data.body.length ; i<ien ; i++ ) {
                html += addRow( data.body[i], 'td' );
            }
            html += '</tbody>';
    
            if ( config.footer && data.footer ) {
                html += '<tfoot>'+ addRow( data.footer, 'th' ) +'</tfoot>';
            }
    
            var frame1 = $("<iframe />");
            frame1[0].name = "frame1";
            frame1.css({ "position": "absolute", "top": "-1000000px" });
            $("body").append(frame1);
            var frameDoc = frame1[0].contentWindow ? frame1[0].contentWindow : frame1[0].contentDocument.document ? frame1[0].contentDocument.document : frame1[0].contentDocument;
    
            // Open a new window for the printable table
            var title = config.title;
    
            if ( typeof title === 'function' ) {
                title = title();
            }
    
            if ( title.indexOf( '*' ) !== -1 ) {
                title= title.replace( '*', $('title').text() );
            }
    
            // Inject the title and also a copy of the style and link tags from this
            // document so the table can retain its base styling. Note that we have
            // to use string manipulation as IE won't allow elements to be created
            // in the host document and then appended to the new window.
            var head = '<title>'+title+'</title>';
            $('style, link').each( function () {
                head += _relToAbs( this );
            } );
    
            try {
                frameDoc.document.head.innerHTML = head; // Work around for Edge
            }
            catch (e) {
                $(frameDoc.document.head).html(head); // Old IE
            }
    
            // Inject the table and other surrounding information
            frameDoc.document.body.innerHTML =
                '<h1>'+title+'</h1>'+
                '<div>'+
                    (typeof config.message === 'function' ?
                        config.message( dt, button, config ) :
                        config.message
                    )+
                '</div>'+
                html;
    
            if ( config.customize ) {
                config.customize(frameDoc);
            }
    
            setTimeout( function () {
                window.frames["frame1"].focus();
                window.frames["frame1"].print();
                frame1.remove();
                frameDoc = null;
                frame1 = null;
            }, 250 );
        },
    
        title: '*',
    
        message: '',
    
        exportOptions: {},
    
        header: true,
    
        footer: false,
    
        autoPrint: true,
    
        customize: null
    };
    
    return DataTable.Buttons;
    }));
    
  • allanallan Posts: 61,722Questions: 1Answers: 10,108 Site admin

    Thanks for suggesting that - looks like an interesting way of resolving it. When I get a chance I'm going to try injecting code into the created document in Buttons and see if that helps to resolve it.

    Allan

  • KW802KW802 Posts: 7Questions: 1Answers: 1

    jvcunha, thank you for posting your solution.

    I ran into this problem today working on some code; I would click the Print button, the new tab would appear but not the print dialog. Curiously if I go back to the first tab then switched back to the print tab that was created then it would continue as normal.

    I tried your code above and so far it seems to be working as expected. B)

  • ab_ninjaab_ninja Posts: 3Questions: 2Answers: 0

    thanks jvcunha ! it works fine for me also.

  • jeffrey_owensjeffrey_owens Posts: 4Questions: 1Answers: 0
    edited January 2018

    Has there been any progress on resolving this problem? jvcunha's fix works for me in Chrome, but I don't get any preview/output in Firefox. (57.0.3 64 bit) (thats using the latest Buttons extension download (1.5.1))

    Just wanted to check before trying to munge up a fix that takes into account whether it's on Firefox or not...

    Thanks!

  • allanallan Posts: 61,722Questions: 1Answers: 10,108 Site admin

    Sorry no - I've not had a chance to fig into this issue yet.

    Allan

  • jvcunhajvcunha Posts: 81Questions: 10Answers: 1

    Hi Jeffrey,
    just change a portion of the code that I made available, testing the browser:

            if ( config.customize ) {
                config.customize(frameDoc);
            }
    
            if (navigator.userAgent.indexOf("Firefox") !== -1) {
                var printWindow = window.open("", "_blank");
                printWindow.document.write('<style>@media print { .no-print, .no-print * { display: none !important; } }</style>');
                printWindow.document.write('<input type="button" id="btnPrint" value="Print" class="no-print" style="width:100px" onclick="window.print()" />');
                printWindow.document.write('<input type="button" id="btnCancel" value="Cancel" class="no-print"  style="width:100px" onclick="window.close()" />');
                printWindow.document.write(head);
                printWindow.document.write('<h1>' + title + '</h1>');
                printWindow.document.write('<div>');
                (typeof config.message === 'function'
                        ? printWindow.document.write(config.message(dt, button, config))
                        : printWindow.document.write(config.message));
                printWindow.document.write('</div>');
                printWindow.document.write(html);
                printWindow.document.close();
                printWindow.focus();
                printWindow = null;
            } else {
                setTimeout(function () {
                    window.frames["frame1"].focus();
                    window.frames["frame1"].print();
                    frame1.remove();
                    frameDoc = null;
                    frame1 = null;
                }, 250);
            }
        },
    
    
  • manuel1021manuel1021 Posts: 1Questions: 0Answers: 0
    edited February 2018

    hi,
    sorry for my bad English.

    I was dealing with this issue and I managed to solve it with:

    if (navigator.userAgent.search("Chrome") >= 0) {
    win.setTimeout( function () {
    if ( config.autoPrint ) {
    win.print();
    win.close();
    }
    }, 250 );
    }else{
    setTimeout( function () {
    if ( config.autoPrint ) {
    win.print();
    win.close();
    }
    }, 250 );
    }

    regards :)

  • allanallan Posts: 61,722Questions: 1Answers: 10,108 Site admin

    Its resolved here and will be in the next release of Buttons.

    Allan

  • sanjeev-shresthasanjeev-shrestha Posts: 2Questions: 1Answers: 0
    edited March 2018

    @allan, i downloaded the fixed version of buttons.print.js file but looks like it only works for Chorme/Opera but when you customize print button, it doesn't work in IE. Any idea??

  • allanallan Posts: 61,722Questions: 1Answers: 10,108 Site admin

    Happy to take a look at a test case showing the issue.

    Allan

  • NeelimaNeelima Posts: 2Questions: 0Answers: 0

    Hi jvcunha,

    I have used your code as I was facing same issue. the issue got resolved but now it is automatically invoking Printer Setup

  • allanallan Posts: 61,722Questions: 1Answers: 10,108 Site admin

    Use the autoPrint option of the print button to disable that.

    Allan

  • NeelimaNeelima Posts: 2Questions: 0Answers: 0

    @allan any update on customise print not working on internet explorer

  • allanallan Posts: 61,722Questions: 1Answers: 10,108 Site admin

    Can you give me a link to a page that shows the issue? This thread is about a Chrome issue.

    Allan

  • rajnarajna Posts: 4Questions: 0Answers: 0

    Customise print is not working on internet explorer for me too...when chrome fix is applied.

  • allanallan Posts: 61,722Questions: 1Answers: 10,108 Site admin

    Happy to take a look at a test case showing the issue.

    Allan

  • allanallan Posts: 61,722Questions: 1Answers: 10,108 Site admin

    I've just tried the nightly version in both Edge and IE. It appears to work as expected for me. As I say, if it isn't for you, please link to a test case showing the issue.

    Allan

  • rajnarajna Posts: 4Questions: 0Answers: 0

    https://datatables.net/extensions/buttons/examples/print/customisation.html

    The print button in the above example doesn't open the print dialog in IE. It just opens the print preview.

  • allanallan Posts: 61,722Questions: 1Answers: 10,108 Site admin

    Yup - its doing that for me in IE11 as well - thanks for pointing that out. I'll check it out.

    Allan

  • rajnarajna Posts: 4Questions: 0Answers: 0

    Any Update please?

  • rajnarajna Posts: 4Questions: 0Answers: 0

    Can anyone please post a solution for print dailog not opening in IE?

  • allanallan Posts: 61,722Questions: 1Answers: 10,108 Site admin

    Sorry - I've not had a chance to dig into this yet. I'll post back when I have.

    Allan

  • allanallan Posts: 61,722Questions: 1Answers: 10,108 Site admin

    I've just tried IE11 with the nightly version of Buttons and it opens the print dialogue box automatically no problem.

    Allan

This discussion has been closed.