Skip to content Skip to sidebar Skip to footer

Check For When A User Has Selected To Print Using Javascript

When a user chooses 'File > Print' on a browser such as Firefox or Internet Explorer, or clicks on a link that runs the below javascript window.print(); Is there a way to condi

Solution 1:

There's a universal solution for this, along with a bit of hackery for older browsers. You can override the print() method in all browsers:

(function (oldPrint) { 
    window.print = function () {
        document.getElementById("hideThis").style.display = 'none';
        oldPrint();
    }
})(window.print);

The problem here is that it will not fire for users pressing Ctrl+P or accessing the file menu to print. Internet Explorer has a solution by way of the onbeforeprint event:

if ("onbeforeprint"inwindow) {
    var hideEl = document.getElementById("hideThis");
    window.onbeforeprint = function () { 
        hideEl.style.display = 'none';
    }
    window.onafterprint = function () {
        hideEl.style.display = '';
    }
}

As for other browsers, you can add an event listener to a print MediaQueryList as detailed by TJ VanToll in another answer:

if (window.matchMedia) {
    var mqList = window.matchMedia("print"),
        hideEl = document.getElementById("hideThis");

    mqList.addListener(function (mql) {
        hideEl.style.display = mql.matches ? 'none' : '';
    }); 
}

And putting it all together:

(function () {
    var hideEl = document.getElementById("hideThis");

    // HTML5 spec, IE 5.5+, Firefox 6.0+if ("onbeforeprint"inwindow) {
        window.onbeforeprint = function () { 
            hideEl.style.display = 'none';
        }
        window.onafterprint = function () {
            hideEl.style.display = '';
        }
    }

    // Chrome 9+, Opera 12.1+, Safari 5.1+elseif (window.matchMedia) {
        var mqList = window.matchMedia("print");

        mqList.addListener(function (mql) {
            hideEl.style.display = mql.matches ? 'none' : '';
        }); 
    }

    // Your fallback method, only working for JS initiated printingelse {    
        (function (oldPrint) { 
            window.print = function () {
                hideEl.style.display = 'none';
                oldPrint();
            }
        })(window.print);
    }
})();

Solution 2:

You can do:

window.old_print=window.printwindow.print=function() {
    alert('doing things');
    window.old_print();
}

but this will only catch calls to print() from inside the page javascript.

Did you try putting !important on print-specific stylesheet?

Post a Comment for "Check For When A User Has Selected To Print Using Javascript"