flowb
flowb

Reputation: 30

How to protect a client side JavaScript variable?

Using the following function to check the existence of a given URL. The code is executed on the client side (browser), is there a way (if at all possible) to protect the url variable from being altered with the browser debugger while keeping the function on the client side?

Note that the url variable is generated by the server and set on the JS script (client side)

function UrlExists(url, callback)
{
    var http = new XMLHttpRequest();
    http.open('HEAD', url);
    http.onreadystatechange = function() {
        if (this.readyState == this.DONE) {
            callback(this.status != 404);
        }
    };
    http.send();
}

Function source.

Upvotes: 0

Views: 935

Answers (4)

Hebe
Hebe

Reputation: 800

You can protect a variable. Declare variable with const keyword in global scope.

const url = 'someValue';

So in case client executes code above first, he cannot redeclare const in same scope later on. However of course client has full control whether to execute some code or not (changing variable name, using different scope, inserting code before).

Upvotes: 0

flowb
flowb

Reputation: 30

While different methods to obfuscate js exist like https://obfuscator.io this does not guarantee any true additional security (but this can make the code not easy to read/debug).

Any thing that is handled on the client side (on the browser js engine), can be altered on the client side with the debugger or with other methods.

Upvotes: 0

Mir
Mir

Reputation: 50

If you are looking to protect the values of variables from being edited or looked at by the console or such, you should look at scoping through IIFE (Immediately Invoked Function Expression).

Since the anonymous function within our IIFE is a function expression and is not being assigned to a global variable, no global property is being created, and all of the properties created inside of the function expression are scoped locally to the expression itself.

This way, any variable you declare and set within this function can not be accessed simply through the window object that your console works in.

If you are looking for some extra security and encrytion, search for JavaScript Obfuscator

Upvotes: 1

Quentin
Quentin

Reputation: 943100

No.

The code runs in the browser. The browser is completely under the control of the user. JavaScript is pretty easy to deobfuscate.

Upvotes: 2

Related Questions