I inherited a website designed for IE that has a print button that prints a specifc, dynamic page using javascript; you press the button for a specific week and it prints the payroll information for that week directly, no new pages are opened. However this functionality doesn't work in non-IE browsers, is there some way to make this work in Firefox/chrome without having to open a new page? I've seen a suggestion to use invisible iframes to load the text and print via that, but that seems to be a lot of changes for what seems a simple task.

The print function is below, the url passed in is the page to print.

function printPayroll(url) {
        var headID = document.getElementsByTagName("head")[0];
        var printNode = document.createElement('link');
        printNode.rel = 'alternate';
        printNode.media = 'print';

        printNode.href = url;
        headID.appendChild(printNode);

        var version = parseInt(navigator.appVersion);
        var browser = navigator.appName;
        if (version >= 4 && browser=="Microsoft Internet Explorer") {
           window.print();
           headID.removeChild(printNode);
        } else {
           alert("Use ctrl + P to print the following page.");
           window.location = printNode.href;
        }
     } 

1 answer

0
points

This looks like a fairly straight-forward function, here's a quick rundown:

  • This function accepts a URL as a parameter, that URL is used if the IE version is greater than 4 (Yikes!)
  • Otherwise, it flows like this:
    1. The function creates a link element in the head section of the page.
    2. It sets some properties of the link element like rel and media to special properties that tell newer browsers (including IE), that there is a special printer-friendly page when the user triggers a print action.
    3. It loads this special page.
    4. It also informs the user via an alert that they should now print using CTRL-P.

That's the long and short of it.

In your case, it'd be much easier to ditch this whole thing (except if you have to support IE 5.5 and lower) and provide a special print CSS in your header. That way, when people go to print, the browser automatically handles things. If you need to preserve the button, you can simply do a quick check to see if the browser qualifies by checking for old IE, then calling window.print();.

Answered almost 7 years ago by Nathan DeGruchy
  • Problem is they're not printing the current page; they're clicking a link (the URL passed to this function) from an index page, and a separate page is printed. That page shouldn't ever be loaded to view for the user if possible, they should stay on the index page. The else alert function is something I put in because the browser just gives you that page in FF/chrome, where in IE it just prints it and leaves you on the index page. Ben Brocka almost 7 years ago