Search code examples
javascriptprintingmozilla

How to prevent Print dialogue in Mozilla from CTRL + P


I have below JavaScript code that gets invoked on pressing CTRL + P on my view. It works on all browsers (tested after updating the userAgent name), but on Mozilla I am not able to block Print Dialogue. What am I doing wrong here?

I am actually trying to add my own logic to print with Ctrl + P (I have multiple i frames on the page and trying to choose which one to print), so after trying for hours, I tried to block it on Mozilla and it turns out that Mozilla still fires the Print dialogue with below code unlike IE 11, Edge, Chrome.

$(document).bind("keyup keydown", function (e) {
if (e.ctrlKey && e.keyCode == 80) {
    var browser = navigator.userAgent.toLowerCase();
    if(browser.indexOf('firefox') > -1)
   {
       return false;
   }}
}

I want to stop the default CTRL + P behavior on Mozilla and run my own script.

This is on MVC web app if at all that matters to anyone.


Solution

  • Personally, I'd use this code

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

    i.e. always, regardless of browser, preventDefault - I'm surprised you don't need to in other browsers