1

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.

6
  • Are you reading a javascript file, then? Commented Oct 11, 2013 at 10:29
  • Or are you making one and want to test it? Commented Oct 11, 2013 at 10:30
  • 3
    Would this include var b = a; if (b){...}? (indirect usage of a) Commented Oct 11, 2013 at 10:30
  • That would be great. But I would be happy to start with direct ones. Like, if(a){...} Commented Oct 11, 2013 at 10:37
  • @Skeptical: then create a parser that finds every conditional statement, creates a hashset of the variables being used within those conditions, then perform the look-up on that hashset. Commented Oct 11, 2013 at 10:41

1 Answer 1

1

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.
Sign up to request clarification or add additional context in comments.

1 Comment

Another alternative to iframe sandboxing would be a capability processor like Caja en.wikipedia.org/wiki/Caja_project

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.