4

Is it possible somehow to prevent users from being able to change JavaScript variables, trough the address bar or with programs like FireBug?

1
  • 1
    Some insight into what your goal is may help us help you find a tamper-proof solution. I can tell you right now that you will need some help from PHP, ASP or other server-side scripting. Apr 19, 2010 at 16:27

5 Answers 5

13

JavaScript is raw source code being interpreted on the client machine, so the short answer is no. The best you could perform as much work as you can on the server. Any JavaScript code you push to the client can be tampered with by the client.

5

This is one of those questions that pretty much begs the response "What is your ultimate goal?"

As stated by others, no, you can't. JavaScript is client side so entirely in the hands of the client, not you.

Obfuscation, as heavyd mentions, could be useful, but it's certainly not a secure/sure-fire way to prevent it.

If this is something you need for security reasons, then the answer is likely that it shouldn't be done with client side JavaScript in the first place.

3

You could create private variables and use an accessor method to get at them

var mySingleton = function(){

    /* here are my private variables and methods */

    var privateVariable = 'something private';

    function showPrivate(){

        console.log(privateVariable);

    }



    /* public variables and methods (which can access private variables and methods ) */

    return {

        publicMethod:function(){

            showPrivate();

        },

        publicVar:'the public can see this!'

    }

}

var single = mySingleton();

single.publicMethod();  // logs 'something private'

console.log(single.publicVar); // logs 'the public can see this!'
3

I'll add my 2 cents for users who come across this page from google.

Use Object.freeze() or Object.seal() to lock an object.
Remember: 'Almost' everything in javascript is an object.
Usage:

var myVariable = {"key1":50};
Object.freeze(myVariable);
myVariable.key1 = 100;//Modifying the value
console.table(myVariable);//Still gives value as 50, rather than 100

Also, these methods are irreversible. So, a user cannot just unseal or unfreeze an object. Although, the user might redefine the variable to a new object itself.

2

No, but you can obfuscate your code to make it difficult to read and reverse engineer.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .