1

I am creating a game and one of the things I am doing to prevent users from inputting code is putting the entire page into a self invoking function. If all of the variables are local, then they will not be accessible outside of the function.

But instead of putting all of the scripts into the same file and putting a function around it, is there a way I could put a function around the javascript that creates the other scripts, or somehow insert the other scripts inside the same function. If not, is there a way I could do this?

Example:

file.js looks like this:

var a = 1;

index.html looks like this:

!function() {
    
  //loads the js file
  var script = document.createElement("script");
  script.setAttribute("src", "file.js");

  //could i do this?
  script.appendChild(script);
    
  //will a be undefined?
  alert(a);
}();
luek baja
  • 1,475
  • 8
  • 20
  • Have you already had a look at [this post](https://stackoverflow.com/questions/950087/how-do-i-include-a-javascript-file-in-another-javascript-file) that explains how to load/import javascript files into other javascript code? – Uchendu Apr 08 '20 at 17:37
  • Yes but create element creates a new element and will not insert the code directly between the script tags. – luek baja Apr 08 '20 at 18:17
  • If you're doing this to try and keep players from calling functions client-side, this won't exactly stop them. They an still just open dev tools, put a breakpoint somewhere and call the function from within the breakpoint scope. Or inject a function to cause those functions to be exposed globally. Just something to keep in mind. – zero298 Apr 08 '20 at 19:13
  • @zero298 Another thing I have done, is disabled keys ctrl, shift, u, i, and right clicking, which means the only other way they could input code into my site is by using bookmarklets, but the function stops that. There are probably still ways that my game could be broken into, but if I can get everything into a function that should be good enough. – luek baja Apr 08 '20 at 19:21

0 Answers0