Do modern browsers support onbeforeprint / onafterprint HTML events?

后端 未结 3 539
既然无缘
既然无缘 2021-01-24 01:58

I am trying to update content of my page for printing. I want to have labels (spans) for each input element (textboxes, lists, etc.) to prevent text-cutoff when printing. I want

相关标签:
3条回答
  • 2021-01-24 02:30

    The MDN page on onbeforeprint is marked as updated last Nov 14, 2013, and it says “no” for Chrome, Opera, and Safari, “(Yes)” for IE, and “6.0” for Firefox. This is consistent with the results of checking with the current Chrome (version 34) and the last Windows version (5.1.7) of Safari. No event is triggered on them, and in developer tools, no onbeforeprint listener is shown under “Event Listeners” in developer tools when onbeforeprint attribute is used.

    There is a WebKit bug report from 2008 about lack of support to beforeprint and afterprint events, and there’s a suggested patch but also issues with it, and it does not seem to be making progress.

    So the answer is “No.”

    Cf. onbeforeprint and onafterprint is not working in Chrome and IE?

    As regards to the possible followup question “What should I use instead, then?”, it should be posted as a new question, with sufficient details (including code) to describe the original problem – in particular, what would be the part that you cannot do by using a print stylesheet.

    0 讨论(0)
  • 2021-01-24 02:33

    Whilst the above answers are excellent in answering the direct question the omit the following essential information:

    Whilst the specific onbeforeprint and onafterprint events are not universally supported, there is functional support for the conceptual events - it IS possible to execute code before and after printing in most modern browsers.

    See here for full details: http://tjvantoll.com/2012/06/15/detecting-print-requests-with-javascript/

    Summary: There exists a window.watchMedia API which allows you to hook into the transition events of CSS media queries, including the 'print' media query. This allows you to hook into events occurring immediately before and immediately after you print a page.

    This API is well supported by Chrome and Webkit, and the onbeforeprint and onafterprint events are supported in IE and Firefox giving you pretty good coverage.

    0 讨论(0)
  • 2021-01-24 02:34

    From MDN onbeforeprint:

    enter image description here


    Well you can always add one event handler to listen for changes and handle updating the content. This is the basic idea [not cross browser friendly]

    document.body.addEventListener("change", function(e){
        var elem = e.target || e.srcElement;
        elem.nextSibling.innerHTML = elem.value;
    });
    

    JSFiddle: http://jsfiddle.net/y4MGE/

    You can use the print style sheet to hide the textboxes when printed and show whatever you want in its place.

    0 讨论(0)
提交回复
热议问题