Are there ways to prevent, or make it difficult enough, for someone to inject Javascript and manipulate the variables or access functions? A thought I had is to change all var n
You can write your JS to use only private methods and variables in a self-executing function. For example, the following code leaves no sign of itself in the global namespace for anyone to monkey with.
(function(){
var x = 1;
var y = 2;
var z = "A am z";
var clickHandler = function() {
alert('You clicked the body');
};
document.getElementsByTagName('body')[0].addEventListener('click',clickHandler,true);
}());
[EDIT]
The above code is susceptible to a user overwriting any globally available objects, methods, events or properties you are using (in this case, document
, getElementsByTagName
and addEventListener
), so if you are truly paranoid you can copy these to your function scope before the page has loaded and the user has a chance to overwrite them. Using addEventListener
is a good idea because unlike the event body.onclick
, it cannot be removed or overwritten from outside the function.