Block code run from the inspect element in JS?

422 Views Asked by At

I have a javascript game that people have started hacking by changing the score variable from the console in the inspect element, is there a way to make it so that code from the inspect element console will not be run?

2

There are 2 best solutions below

3
On BEST ANSWER

I would use scoped variables, so the attacker can't access them from the console.

const unscoped = "you can reach me from the console";
console.log(unscoped);

{
  const scoped = "you can NOT reach me from the console";
}
console.log(scoped);

Another option would be to wrap all of your code in an Immediately Invoking Function Expression (IIFE):

"use strict";
(function game() {
  //code goes here
  for (var score = 0; score <= 5; score++) console.log("Score: ", score);
})();

console.log("Attacking attempt:");
console.log(score);

EDIT: that last one requires you to use strict mode (type "use strict"; at the beginning of the file)

1
On

i found this code it can be helpful:

<script>
/* To Disable Inspect Element */
$(document).bind("contextmenu",function(e) {
 e.preventDefault();
});

$(document).keydown(function(e){
    if(e.which === 123){
       return false;
    }
});
</script>

refrence:

https://www.codingtag.com/how-to-disable-inspect-element