How to block the browser console using javascript?

I would like to know how to block the user from running scripts through the browser console.

 12
Author: Cabeção, 2014-02-16

3 answers

Edit: This code no longer works in Google Chrome.


In fact, it is possible to block the Google Chrome console just as Facebook has been doing, with the following code:

var _z = console;
Object.defineProperty(window, 'console', {
    get: function(){
        if (_z._commandLineAPI) {
            throw new Error('console bloqueado');
        }
        return _z;
    },
    set: function(val) {
        _z = val;
    }
});

Open the Google Chrome console on the Facebook page and see for yourself (does not appear for all users):

insert the description of the image here


References:

 8
Author: Comunidade, 2017-05-23 12:37:30

Is not possible. The page is submissive to the browser and the javascript console is not something you can actually control, it's an extra. It would be like preventing them from seeing your html or creating a file .txt that could not be edited, it makes no sense.

The user is completely free to edit anything of your page. Any code can be changed and any validation done purely in JS can be circumvented. That's why the server should never trust something coming from the client.

 13
Author: Guilherme Bernal, 2014-02-16 23:03:04

Sorry guys, but as for the answer about Facebook being disabling the console only displaying that message. Don't check.

What Facebook does is simply display a warning to the user not to use the console and for this displays the mansage using the console object in Javascripr. I do this in my projects to create a signature that is displayed in the console. See what I do in the main Javasript of the site:

style = "color:blue;font-size:1.1em;";
style2 = "color:green; font-weight:bold;font-size:1.1em;";
console.groupCollapsed("Creditos do desenvolvedor:");
   console.info("%c-------------------------------------------------------------",style);
   console.info("%cEste é mais um site desenvolvido pela...", style2);
   console.info("%chttp://www.site.com.br",style);
   console.info("%cTodos os direitos reservados © 2017",style);
   console.info("%c-------------------------------------------------------------",style);
   console.info("");
console.groupEnd();
 2
Author: Jorge Rodrigues, 2018-09-04 20:55:16