The title suggests that events exist to cause action when a document is printed from a web browser. Well, they do, technically. But, technically, they don't work that well!

The events we're talking about are onbeforeprint and oneafterprint. At this point, I believe the latest version of all modern browsers reports to have this functionality, however, my trials suggest otherwise.

I have not tested it in IE, although they were the first on the scene with support for these events, so I would hope that they work well. In testing Firefox, disappointment, neither event fired for me. In Chrome, onbeforeprint did not fire.

One of my clients required this feature, as a means to track when a given page had been printed – a really novel idea, I thought. But, this was on a public facing site, so I could not rely on the sketchy implementations of the print events described above.

I instead, opted for a CSS solution – crazy right! I can't believe how often we turn to CSS when least expected (device detection, drop down menus, image manipulations, etc.). Well, add this one to the list.

By supplying a processing script as the background image of the body, within a print stylesheet, I was able to accomplish this.

<style type="text/css">
@media print {
  body { background: url(/scripts/updatePage.php?page_id=<?php echo $_GET['page_id']; ?>); }
}
</style>

By creating an updatePage.php script, which accepts a page_id in the query string as show above, you are able to take action when a user attempts to print a document.

Semantics are important here. Notice, I use the word attempts in the previous sentence. Again, not testing Internet Explorer, I found that FireFox will call your script only after the document has printed. While Google Chrome will call it before hand.

This entirely depends on when the browser needs the background image for the printed page. Or, at least what the browser thinks is an image. We put these browsers through such abuse!

Tags:

Leave a Reply

Your email address will not be published. Required fields are marked *