开心网acc的取得,java调用javascript的函数

参考

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();
		}

	}

}

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值