Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Force open the details / summary tag for Print in Chrome

I try to print the content of the details tag in Chrome but I can't force it to open.

This is what I have in my print CSS :

details, details > * { display:block !important; }

But the content appear only if I open the details before printing the page.

Is there any way to force opening details by css print on chrome ?

like image 438
Val Entin Avatar asked Oct 20 '22 21:10

Val Entin


2 Answers

Reasonable cross-browser solution with jQuery (not Opera)...adapted from https://www.tjvantoll.com/2012/06/15/detecting-print-requests-with-javascript/:

// Set up before/after handlers
var beforePrint = function() {
    $("details").attr('open', '');
};
var afterPrint = function() {
    $("details").removeAttr('open');
};

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

// IE, Firefox
window.onbeforeprint = beforePrint;
window.onafterprint = afterPrint;
like image 115
neil Avatar answered Oct 24 '22 11:10

neil


I found the solution by forcing the opening details tag with BeforePrint and Afterprint

class App.Views.main extends backbone.View
el : "body"
events : 
    "click [data-auto-focus]":"autoFocus"
initialize : () ->
    # Add conditional classname based on support
    $('html').addClass( (if $.fn.details.support then 'details' else 'no-details'))
    $('details').details()

    if (window.matchMedia)
        mediaQueryList = window.matchMedia('print')
        mediaQueryList.addListener (mql) =>
            if (mql.matches)
                @beforePrint()
            else 
                @afterPrint()

    window.onbeforeprint = => @beforePrint
    window.onafterprint = => @afterPrint

render : () ->

openedDetailsBeforePrint : null

beforePrint : () ->
    console.log "before print"
    @openedDetailsBeforePrint = @$el.find('details[open], details.open')
    if ($('html').hasClass('no-details')) then @$el.find('details').addClass("open") else @$el.find('details').attr("open", "")

afterPrint : () ->
    console.log "after print"
    @$el.find('details').removeClass(".open").removeAttr("open")
    if ($('html').hasClass('no-details')) then @openedDetailsBeforePrint.addClass("open") else @openedDetailsBeforePrint.attr("open", "")


autoFocus : (e) ->
    $element = if (e.currentTarget) then $(e.currentTarget) else $(e.srcElement)
    return $($element.attr "data-auto-focus").focus()
like image 38
Val Entin Avatar answered Oct 24 '22 09:10

Val Entin