Cookies
Cookies

Reputation: 685

Check if a Javascript variable is used in any if statement

I want to check whether a given Javascript variable goes is used by any IF statements inside the program. Is there a way to dynamically do this rather than pure static code analysis.

Am not reading any file here. Lets say that I can inject a piece of JS code using some extension during run time and dynamically find if a given variable goes through an IF statement.

Upvotes: 1

Views: 151

Answers (1)

Joe
Joe

Reputation: 47739

This is a bad idea. There are lots of things that could go wrong. You could look into sandboxing.

But, as long as you aren't relying on this for security, you might find this useful:

var x = function (a, b, c) { if(a) {console.log(a)}};
var y = function (a, b, c) { if(b) {console.log(a)}};

// You can get the text of a function. Notice it's been formatted.
console.log(x.toString());
>>> "function (a, b, c) { if (a) { console.log(a) } }"

var matcher = /if ?\(.?a.?\)/g;

x.toString().match(matcher);
>>> ["if (a)"]

y.toString().match(matcher);
>>> null

Things to be careful of, off the top of my head:

  • Different browsers may format the code differently.
  • Variables can be aliased by assigning them to a different name.
  • Variables can be accessed by index-access and strings.
  • This is a naïve regular expression and will obviously match if (nota).
  • Your javascript will be visible, so anyone who wants to get round this will find a way.

Upvotes: 1

Related Questions