Skip to content

How to override standard browser print and print an iframe by default

I have a documentation type page with an iframe inside. I’m trying to override standard browser print (Ctrl + p) to print contents of an iframe only.

I know how to print an iframe content using javascript:


I know how to do run javascript before printing e.g. as described here: Check for when a user has selected to print using javascript

Any advise?



It’s not possible (using Javascript). There is some experimental support for user-initiated print events in modern browsers, but those are not cancelable (“simple events”) so the entire page will still print even if you interject custom code to print the frame of interest.

Given this limitation, your best bet is probably to offer users a large button that fires your custom frame printing function (see printContentFrameOnly below, fire it without arguments) and hope that they’ll use the button instead of ctrl-p.

If it would be possible, this would be the way to do it (based on this answer):

// listener is a function, optionally accepting an event and
// a function that prints the entire page
addPrintEventListener = function (listener) {

    // IE 5.5+ support and HTML5 standard
    if ("onbeforeprint" in window) {
        window.addEventListener('beforeprint', listener);

    // Chrome 9+, Firefox 6+, IE 10+, Opera 12.1+, Safari 5.1+
    else if (window.matchMedia) {
        var mqList = window.matchMedia("print");

        mqList.addListener(function (mql) {
            if (mql.matches) listener();  // no standard event anyway

    // Your fallback method, only working for JS initiated printing
    // (but the easiest case because there is no need to cancel)
    else {    
        (function (oldPrint) { 
            window.print = function () {
                listener(undefined, oldPrint);

printContentFrameOnly = function (event) {
    if (event) event.preventDefault();  // not going to work