Printing a page

  • window.print() works in Netscape 4 and 6, Explorer 5+ on Windows, Opera 6, iCab, Ice Browser and Hotjava 3, while WebTV says it supports the method but don't actually do something.
  • The VBScript on this page works in Explorer 4, 5 and 6 on Windows (though only 4 really needs it).

    An often requested functionality is the Print link, with which users can print out a page. This can be very useful in framed sites when you don't want to explain to the user he has to click on the correct frame, then press "Print" etc.

    I'm not yet content with the way the script is built up. I discovered some quite serious trouble connecting JavaScript and the VBScript we need for Explorer 4. I'm probably going to rewrite it later on.


    As usual, you can try the script. I added my browser detect so you can keep track of which print was produced by which browser.

    The script

    <SCRIPT LANGUAGE="JavaScript" TYPE="text/javascript">
    var VBS = false;
    // -->
    <script language="VBScript">
    sub window_onunload
            on error resume next
            set WB = nothing
    end sub
    function printIt
    '	on error resume next
    	call WB.ExecWB(6,1)
    '6,2 gives no alert
        if err.number <> 0 then
             if DA then ' Internet Explorer 4 they probably cancelled
                         alert "Nothing Printed :" & err.number & " : " & err.description
                 handle_error '  ie3x give alternate instructions
             end if
        end if
    end function
    document.write  "<OBJECT ID=""WB"" WIDTH=0 HEIGHT=0 CLASSID=""CLSID:8856F961-340A-11D0-A96B-00C04FD705A2""> </OBJECT>"
    VBS = true
    <SCRIPT LANGUAGE="JavaScript" TYPE="text/javascript">
    /* The actual print function */
    function prePrint()
    	if (window.print) window.print();
    	else if (VBS) printIt();
    	else alert('This script does not work in your browser');
    // -->

    In the print link, call the function prePrint() which finds out for you whether the browser supports printing and, if so, if it must be done by JavaScript or VBScript.

    Short explanation

    Since I'm going to rewrite this script later, I'll keep the explanation short.

    In JavaScript the theoretical way to print a frame or window is


    This works in Netscape 4 and up, iCab, Hotjava and (on Windows) Explorer 5 and up. The other browsers can't handle this, except for Explorer 4 on Windows (and, it is rumoured, Explorer 3). Here we use the VBScript to create an Object that holds an instance of the browser and give it ID="WB"

    document.write  "<OBJECT ID=""WB"" WIDTH=0 HEIGHT=0 CLASSID=""CLSID:8856F961-340A-11D0-A96B-00C04FD705A2""> </OBJECT>"

    and then we call the function WB.ExecWB(6,1) which means print.

    call WB.ExecWB(6,1)

    I'm still not entirely sure how this works, more news later.

    Printing other frames

    When printing other frames in Explorer it is necessary to put the focus on them first: