views:

31

answers:

2

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 conditionally check for this mode and disable SOME javascript.

I am trying to do this because I have a plugin that adds in its own custom markup for rounded borders and even in a print specific stylesheet I can not override the styling for these, I dont want the borders to appear when printing out the page.

EDIT: Unrelated to the plugin there are style changes done via javascript that is used to create a tabbed user interface and I have done print specific CSS to override the styling and it works fine when I use the Firefox web developer toolbar > CSS > Display CSS by Media type > Print.. but when I print it out it doesn't work, the javascript takes over and changes the styling.. if I disable javascript completely then the printing obviously works fine again.

Thanks

+2  A: 

You can do:

window.old_print=window.print
window.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?

aularon
Both answers make it pretty clear that I can't cover every case so I am in a bit of a pickle. Thanks for the help.
Pricey
+1  A: 

There's no universal solution for this. 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" in window)
    window.onbeforeprint = function () { 
        document.getElementById("hideThis").style.display = 'none';
    }

Unfortunately, that doesn't help in other browsers. A combination of both of the above would catch a lot of cases but there's no perfect solution.

Andy E