0

I need to do a static analysis of Javascript files using Java. Here I need to check whether the Javascript file has any function calls to document.write() or reference to properties like innerHTML etc. Can I use javax.script.* package to achieve this? or Which Java api do I need to use for Parsing? Also can you provide examples for the same?

1

1 Answer 1

2

You can't statically analyze Javascript in the way you intend because Javascript is not a statically typed language.

You can check for document.write() but what if my code was this:

var whatever = document; whatever.write()

Or do you want to reject any function named write() even if it didn't write to the document?

Furthermore, Javascript has an eval function so you could always do:

var m = "ment"; 
eval("docu" + m + ".wri" + "te('hahahaha')");`.

How are you going to check for that?

Similarly, property access can be done in many ways.

Imagine this piece of code:

var x = document.children[0];
x.innerHTML = ...;
x["inner" + "HTML"] = ...;
var y = "inner";
x[y + "HTML"] = ...;

You're not going to be able to detect all those variants, and the hundreds more variants that you could make, using static analysis.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the wonderful answer. Can this be achieved through any dynamic solution using Java? I just want to check whether the calls to these functions/properties is made. This is just to get the statistics of those function calls.
You can only do that by running the code and somehow counting the number of calls. There is a Javascript engine in Java but it doesn't emulate the browser well enough (I've never used to to emulate a browser, it may not have this functionality at all) to run most javascript scripts. Your best bet is to look into PhantomJs, which does emulate a modern browser (but not in Java) - you may be able to plug your own code into it to do what you want.

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.