参考
http://www.cnblogs.com/yesun/archive/2008/04/02/1134041.html
http://heisetoufa.iteye.com/blog/227714
package com.kaixin001.common;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.LineNumberReader;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.mozilla.javascript.Context;
import org.mozilla.javascript.Function;
import org.mozilla.javascript.Scriptable;
public class ScriptHelper {
private Context cx;
private Scriptable scope;
public ScriptHelper() {
this.cx = Context.enter();
this.scope = cx.initStandardObjects();
}
public Object runJavaScriptByFile(String filename) {
String jsContent = this.getJsContent(filename);
Object result = cx.evaluateString(scope, jsContent, filename, 1, null);
return result;
}
public Object runJavaScript(String jsContent) {
Object result = cx.evaluateString(scope, jsContent, "", 1, null);
return result;
}
private static String getJsContent(String filename) {
LineNumberReader reader;
try {
reader = new LineNumberReader(new FileReader(filename));
String s = null;
StringBuffer sb = new StringBuffer();
while ((s = reader.readLine()) != null) {
sb.append(s).append("\n");
}
return sb.toString();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}
public Scriptable getScope() {
return scope;
}
public static void main(String[] args) throws FileNotFoundException, IOException {
String filename = System.getProperty("user.dir") + "/acc.htm";
// String pattern = "";
String accCode = "";
String script = "";
String script_tmp2 = "";
String var_values = "";
// 得到所有script段
Pattern pattern = Pattern.compile("<script type=\"text/javascript\">.*?</script>", Pattern.DOTALL);
Matcher matcher = pattern.matcher(getJsContent(filename));
String jsContent = "";
while (matcher.find()) {
String js = matcher.group();
if(js.contains("function acc()")) {
jsContent = js.replaceAll("<.*?script.*?>", "");
//System.out.println(jsContent);
}
}
String jsFunction = "acc";
// 开始调用javascript函数
Context cx = Context.enter();
try {
Scriptable scope = cx.initStandardObjects();
cx.evaluateString(scope, jsContent, null, 1, null);
Object fObj = scope.get(jsFunction, scope);
if (!(fObj instanceof Function)) {
System.out.println("找不到方法" + jsFunction);
} else {
Function f = (Function) fObj;
Object result = f.call(cx, scope, scope, null);
System.out.println("返回结果:" + Context.toString(result));
}
} finally {
Context.exit();
}
}
}