简体   繁体   English

从Java获取javascript函数的参数值?

[英]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. 对于我的Java应用程序,我需要能够在给定JavaScript字符串的情况下确定传递给函数调用的实际参数。

For example, given this JavaScript string: 例如,给定以下JavaScript字符串:

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: 我想评估此JavaScript,以获取此信息:

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. 现在,我正在使用正则表达式来查找我感兴趣的JavaScript部分(在此示例中,这将是XMLHttpRequest对象的open方法),但是我需要能够计算JavaScript的实际值。传递给函数的参数(如果未从调用端对其进行硬编码)。

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). 我一直在这里搜索,但是发现的内容与实际执行JavaScript代码更相关,而不是查看其表达式值(更像是评估它,获取AST之类)。

Any ideas on how to accomplish this? 关于如何做到这一点的任何想法?

My idea is to add some javascript mocking library like sinon and execute this javascript. 我的想法是添加一些JavaScript 模拟库(例如sinon)并执行此javascript。 Especially take a look at fake XMLHttpRequest 特别看看伪造的XMLHttpRequest

Javascript code will like this: Javascript代码将如下所示:

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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