Home > Database > Mysql Tutorial > body text

How to Reliably Detect Print Requests Across Multiple Browsers?

Linda Hamilton
Release: 2024-11-02 14:05:30
Original
901 people have browsed it

How to Reliably Detect Print Requests Across Multiple Browsers?

Cross-Browser onbeforeprint() and onafterprint() Solution

Detect when a web page is being printed across various browsers has been a challenge in the past due to the absence of a unified approach. Traditionally, Internet Explorer provided the onbeforeprint() and onafterprint() events for this purpose, but other browsers lacked equivalent functionality. However, recent advancements have introduced new possibilities.

Utilizing window.matchMedia

Many modern browsers now support the window.matchMedia API, which allows for the detection of CSS media query changes. By employing window.matchMedia in conjunction with window.onbeforeprint/window.onafterprint, a cross-browser solution can be achieved.

The following code snippet demonstrates the implementation:

if ('matchMedia' in window) {
    // Chrome, Firefox, and IE 10 support mediaMatch listeners
    window.matchMedia('print').addListener(function(media) {
        if (media.matches) {
            beforePrint();
        } else {
            // Fires immediately, so wait for the first mouse movement
            $(document).one('mouseover', afterPrint);
        }
    });
} else {
    // IE and Firefox fire before/after events
    $(window).on('beforeprint', beforePrint);
    $(window).on('afterprint', afterPrint);
}
Copy after login

Benefits and Caveats

This approach offers a cross-browser solution for detecting print requests. However, it's essential to note that some browsers may trigger multiple calls to beforePrint() and afterPrint(), potentially leading to undesirable behavior. Therefore, it's crucial to carefully consider the processing requirements in response to the print event.

Further Resources

For more information and examples, refer to the following external resource:

  • [Detecting Print Requests with JavaScript](http://tjvantoll.com/2012/06/15/detecting-print-requests-with-javascript/)

The above is the detailed content of How to Reliably Detect Print Requests Across Multiple Browsers?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!