0

For my Java application I need to be able of, given a JavaScript string, determine the actual arguments passed into a function call.

For example, given this JavaScript string:

const url = "http://foo.bar?q=" + location.href
const method = "GET"
const isAjax = true

let xmlhttp = new XMLHttpRequest();
xmlhttp.open(method, url, isAjax);

I would like to evaluate this JavaScript in order to get this:

xmlhttp.open("GET", "http://foo.bar?q=someurl", true);

Right now I'm using a regex to look for the parts of the JavaScript I'm interested in (in this example it would be the open method of the XMLHttpRequest object), but I need to be able to compute the actual values of the arguments passed to a function, if they are not hardcoded from the call-side.

I have been searching here but what I found was more related to actually executing the JavaScript code rather than looking at its expressions values (more like evaluating it, getting an AST or something like that).

Any ideas on how to accomplish this?

Ahmed Ashour
  • 5,179
  • 10
  • 35
  • 56
fergaral
  • 2,077
  • 6
  • 17
  • 34
  • Not possible in example case because you wouldn't know the value of `location.href` unless you actually run this script on the side of a client browser. You could try running the script with Nashorn engine, but I doubt it'll do what you expect it to, since the requirement is so vague. – M. Prokhorov May 23 '18 at 12:12
  • Yes, that's true. Actually, these JavaScript files come from actual webpages, I download them from a crawler and then process them – fergaral May 23 '18 at 12:22
  • In this definition of your problem, you will need to rewrite all javascript you've downloaded in a very specific way, and then run it to get parameters out. There wouldn't be any general solution that would make a good SO answer. I assume you would already know how to run a headless browser of script engine since you're scraping JS. – M. Prokhorov May 23 '18 at 12:25

1 Answers1

0

My idea is to add some javascript mocking library like sinon and execute this javascript. Especially take a look at fake XMLHttpRequest

Javascript code will like this:

let sinon = require('sinon');
let xhr = sinon.useFakeXMLHttpRequest();
let requests = [];
xhr.onCreate = function (xhr) {
        requests.push(xhr);
    }
const url = "http://foo.bar?q=" + location.href
const method = "GET"
const isAjax = true

let xmlhttp = new XMLHttpRequest();
xmlhttp.open(method, url, isAjax);

console.log(requests[0].url)
Bartek Jablonski
  • 2,649
  • 24
  • 32