简体   繁体   中英

Get values of parameters of javascript function from Java?

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?

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM