18

Here I tried to disable the Ctrl+P but it doesn't get me alert and also it shows the print options

jQuery(document).bind("keyup keydown", function(e){
    if(e.ctrlKey && e.keyCode == 80){
        alert('fine');
        return false;
    }
});

http://jsfiddle.net/qaapD/10/

I am not sure how can I disable the Ctrl+P combination itself using jQuery or JavaScript.

Thanks

Pavlo
  • 43,301
  • 14
  • 77
  • 113
Vignesh Pichamani
  • 7,950
  • 22
  • 77
  • 115
  • 1
    Thanks for all. I working on project which is print our custom data when you click the print button not the shortcut that so i posted in Stackoverflow – Vignesh Pichamani Sep 17 '13 at 07:43
  • 3
    why not support both? – Bobby Jack Sep 17 '13 at 07:43
  • If you are 100% sure your users will only be working with one OS this is a solution, but I agree with the other comments, you should support other platforms as well. – Morne Sep 17 '13 at 07:48
  • 3
    I suggest using print styling to show the custom data you want and hide the content you don't want printed. You can use css to hide the custom data from the screen if you don't want it to appear there. This way, users can use any method of printing the page, and always end up with the print out you want them to have. – 3dgoo Sep 17 '13 at 07:51
  • Thanks for your suggestion @3dgoo I finally did using css – Vignesh Pichamani Sep 17 '13 at 07:55
  • @3dgoo that's actually a brilliant compromise/suggestion – Bobby Jack Sep 17 '13 at 07:55

12 Answers12

26

You can't prevent the user from printing, but you can hide everything when the user prints the document by using simple CSS:

<style type="text/css" media="print">
    * { display: none; }
</style>

Updated fiddle.

If you would like to show the visitor a custom message when he/she try to print rather then just a blank page, it's possible with client side code but first wrap all your existing contents like this:

<div id="AllContent">
    <!-- all content here -->
</div>

And add such a container with the custom message:

<div class="PrintMessage">You are not authorized to print this document</div>

Now get rid of the <style type="text/css" media="print"> block and the code would be:

if ('matchMedia' in window) {
    // Chrome, Firefox, and IE 10 support mediaMatch listeners
    window.matchMedia('print').addListener(function(media) {
        if (media.matches) {
            beforePrint();
        } else {
            // Fires immediately, so wait for the first mouse movement
            $(document).one('mouseover', afterPrint);
        }
    });
} else {
    // IE and Firefox fire before/after events
    $(window).on('beforeprint', beforePrint);
    $(window).on('afterprint', afterPrint);
}

function beforePrint() {
    $("#AllContent").hide();
    $(".PrintMessage").show();
}

function afterPrint() {
    $(".PrintMessage").hide();
    $("#AllContent").show();
}

Code is adopted from this excellent answer.

Updated fiddle. (showing message when printing)

Community
  • 1
  • 1
Shadow The GPT Wizard
  • 66,030
  • 26
  • 140
  • 208
  • 4
    wouldn't that print a blank page, other than header/footer, wasting ink and paper? way to piss off your users... – Bobby Jack Sep 17 '13 at 07:45
  • @BobbyJack better than blocking CTRL+P which will just make them wonder what's wrong with their keyboard... :) – Shadow The GPT Wizard Sep 17 '13 at 07:46
  • 1
    if you absolutely had to disable Ctrl+p (which, of course, everyone knows you should never do) it would probably be nice to mention that you'd done it with an inline message / popup dialog when Ctrl+p is pressed. – Bobby Jack Sep 17 '13 at 07:48
  • your code was not working for me (**FF 31**), but **this very similar code did it** (did not have a closer look why): http://tjvantoll.com/2012/06/15/detecting-print-requests-with-javascript/ (see ***Combining the Approaches***) – Andreas Covidiot Jan 11 '15 at 01:44
  • **Chrome 39.0 and IE 11.0 did not work with yours either** with yours, but at least **IE 11.0 runs as well with the code mentioned in my post above**. also posted in short here: http://stackoverflow.com/a/11060206/1915920 – Andreas Covidiot Jan 11 '15 at 02:56
  • Thanks @ShadowTheVaccinatedWizard!! I was lookin for this code since morning. – Neel Dsouza Apr 04 '21 at 09:17
15

After much testings on various browsers, it is easier to intercept the keys when they are down (not pressed) because some of this "App integrated keys" are difficult to intercept with the "keypress" event.

I came up with this script that is sort of cross browser compatible (I didn't test for Microsoft's IE). Notice that the browsers return different codes for some keys. In my case I wanted to prevent Ctrl+P.

The key "P" on chrome is seen as e.keyCode == 80, on opera, it is e.charCode == 16, while on firefox it is e.charCode == 112

$(document).on('keydown', function(e) {
    if((e.ctrlKey || e.metaKey) && (e.key == "p" || e.charCode == 16 || e.charCode == 112 || e.keyCode == 80) ){
        alert("Please use the Print PDF button below for a better rendering on the document");
        e.cancelBubble = true;
        e.preventDefault();

        e.stopImmediatePropagation();
    }  
});

I used jQuery.

Peter
  • 6,509
  • 4
  • 30
  • 34
3

This is basically Peters answer from above. The difference is I added the accountability for mac when pressing the cmd+p button combo to print a page.

$(document).on('keydown', function(e) { 
    if((e.ctrlKey || e.metaKey) && (e.key == "p" || e.charCode == 16 || e.charCode == 112 || e.keyCode == 80) ){
        alert("Please use the Print PDF button below for a better rendering on the document");
        e.cancelBubble = true;
        e.preventDefault();

        e.stopImmediatePropagation();
    }  
});
schwar_01
  • 51
  • 2
2

To disable Ctrl+P printing by using javascript use below code:

window.addEventListener('keydown', function(event) {
    if (event.keyCode === 80 && (event.ctrlKey || event.metaKey) && !event.altKey && (!event.shiftKey || window.chrome || window.opera)) {
        event.preventDefault();
        if (event.stopImmediatePropagation) {
            event.stopImmediatePropagation();
        } else {
            event.stopPropagation();
        }
        return;
        }
}, true);
Pranit More
  • 496
  • 5
  • 13
1

Your code works in the jsfiddle example? What browser are you using? Itested it with the latest chrome and it worked fine.

You can also add:

e.preventDefault();
Morne
  • 1,623
  • 2
  • 18
  • 33
1

This Actually worked for me in chrome. I was pretty suprised.

jQuery(document).bind("keyup keydown", function(e){
    if(e.ctrlKey && e.keyCode == 80){
         Print(); e.preventDefault();
    }
});

Where Print is a function I wrote that calls window.print(); It also works as a pure blocker if you disable Print();

As noted here: https://stackoverflow.com/a/20121038/2102085

window.print() will pause so you can add an onPrintFinish or onPrintBegin like this

function Print(){
    onPrintBegin
    window.print();
    onPrintFinish(); 
}

(Again this is just chrome, but Peter has a downvoted solution below that claims the keycodes are different for ff and ie)

Community
  • 1
  • 1
Jack Franzen
  • 768
  • 7
  • 21
1

had a journy finding this, should be canceled on the keydown event

document.addEventListener('keydown',function(e){
   e.preventDefault();
   return false;
});

further simplified to :

document.onkeydown = function(e){
   e.preventDefault();
}

given you have only one keydown event

1

Here is the code, it work for me

document.addEventListener("keydown", function(event) {
  if (event.ctrlKey && event.key === "p") {
    event.preventDefault();
  }
});
Sourav Pan
  • 11
  • 2
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Feb 05 '23 at 00:09
0

there are some shortcuts you simply can't override with javascript, i learned it the hard way. I suppose CTRL+P is one of them.

one way to override them would be to deploy a chrome pacakged app.

lordvlad
  • 5,200
  • 1
  • 24
  • 44
0

Try this

    //hide body on Ctrl + P
    jQuery(document).bind("keyup keydown", function (e) {
        if (e.ctrlKey && e.keyCode == 80) {
            $("body").hide();
            return false;
        }
    });
-1
<script>
      function isKeyPressed(event) 
      {
        if(event.ctrlKey == 1)
        {
          alert("Please Submit exam form befor printing");
        }
      }
    </script>

<body onkeydown="isKeyPressed(event)">
<p>this is the solution</p>
</body>
Gufran Hasan
  • 8,910
  • 7
  • 38
  • 51
-4

If you want to disable printing of your webpage you're wasting your time: it can't be done. Even if you work out how to capture CTRL-P users can still use the browsers menu bar to find the print command, or they can take a screen shot of the browser.

Stop trying to control the user, put your energy into making your site / app more useful, not less useful.

edit 2016: in the 3 years this has been up it has gathered 3 downvotes. I'm still not deleting it. I think it is important to tell fellow developers when they are given impossible tasks, or tasks that make no sense.

edit 2018: still think it's important that people that have this question read this answer.

bjelli
  • 9,752
  • 4
  • 35
  • 50
  • 15
    You're guessing the intentions of the author, a legitimate use could be overriding ctrl p as a shortcut for something else in the author's application. – simonzack Sep 17 '13 at 07:41
  • 4
    This doesn't answer the question. – Pavlo Sep 17 '13 at 07:43
  • 3
    Just because an answer doesn't directly address the question, doesn't make it invalid. If it points out best practice and steers the asker away from a path that would lead to danger, "you shouldn't do that" is actually a *better* answer than something which addresses the question without such warning. – Bobby Jack Sep 17 '13 at 07:53
  • 2
    @BobbyJack OP asks how to disable Ctrl + P combination, bjelli rants about disabling printing. This is not UX Stackexchange, we are addressing programming issues here. – Pavlo Sep 17 '13 at 09:23
  • 2
    @Pavlo: I think it's a fine line. If someone posted code that was hugely inefficient, along with a question asking about something very specific, and unrelated, it would probably still be good to highlight the inefficiencies. Even though somebody doesn't explicitly ask for something, it's still helpful to point it out if it's beneficial. – Bobby Jack Sep 17 '13 at 11:31
  • 2
    @BobbyJack An answer saying it is waste of time or make something useful does not contribute as an answer. His point is trivial, you cannot stop users from printing. Here OP only needs to disable Ctrl + P, he does print something. – user568109 Sep 17 '13 at 11:40
  • 1
    Go to facebook.com and press ctrl+p. Or pretty much any site. I bet they wish they had it disabled. The reason he's asking is because you can't use a custom printer with the ctrl+p shortcut running. If you can disable it, you can write a replacement script to style the page before printing – Jack Franzen Apr 27 '15 at 16:58
  • 1
    What about a webcontrol integrated in a desktop application. There is no menu, so you can't print via the menu. The purpose of an embedded webcontrols could be to only show content, and not provide a full blown web browser experience. Hence it makes sense to disable CTRL+P, especially if the host application is a report generating application, and the HTML pages are solely input... as in my case. That is not controlling the user, that is setting boundaries to what the use cases of the embedded webcontrol should allow. – Mike de Klerk Jan 14 '16 at 10:10
  • 1
    Sorry but I had to downvote, because this not only doesn't answer the question; its willfully unaware of legitimate usecases, which there are many in certain domains -especially Intranet applications. – the_5imian Dec 16 '16 at 17:39
  • 2
    Sometimes people have a very good reason to do something - lecturing them like "what you want to achieve is silly, don't even want it" is the opposite of helping. See, for example, I'm looking for a way to disable this key combo because my "browser" is embedded and Ctrl+P should not print the "web page" inside it, it's not even a web page. The application needs this shortcut, the browser should not react on it. Duh. Teaching people what to do with their own projects is a lot worse than capturing a key you don't like to be captured. – dkellner Apr 11 '18 at 21:50