0

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?

LlamaButt
  • 431
  • 4
  • 15

2 Answers2

1

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)

  • so this solution stores the variable in an unnamed object literal? how does that make it inaccessible to the console? – LlamaButt May 07 '21 at 20:44
  • It uses scoping; basically, when you define variables locally (within `{ }` curly braces), they can only be accessed *within* that scope (so within those curlies). The console context is always the `window` object, so those variables will not be defined. –  May 07 '21 at 20:47
  • So no, it is not an unnamed object literal, it is a code block: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/block –  May 07 '21 at 20:49
-1

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