关于java调用js,document不能用问题

1.

 Document mydoc = null;
 public BareBonesBrowserLaunch(String url) throws MalformedURLException, IOException{
  mydoc = Jsoup.parse(new URL(url),30000);//利用Jsoup实现document树
 }

2.

public Element getElementById(){//实现document的方法
  System.out.println("Java println:\t"+mydoc.getElementById(id));
  return mydoc.getElementById(id);//返回的是Element对
 }

3.java中调用js

/**
  * 调用js中的方法
  * @throws Exception
  */
 public static void ExcuteJs(String url) throws Exception{
  ScriptEngineManager sem = new ScriptEngineManager();
  ScriptEngine se = sem.getEngineByName("JavaScript");
  String path =this.getServlet().getServletContext().getRealPath("/WEB-INF/js/jituan.js");
  
  File f = new File(path);
  Reader d = new InputStreamReader(new FileInputStream(f));
  se.eval(d); 
  Invocable inv = (Invocable) se;
  se.put("document", new BareBonesBrowserLaunch(url));关联对象,很重要,关联javascript的document对象为BareBonesBrowserLaunch,即自己实现的document对象
  String value = (String) inv.invokeFunction("load",url);
  
  System.out.println(value);
  
  
 

//直接调用js方法 

//  ScriptEngineManager factory = new ScriptEngineManager();
//  ScriptEngine scriptEngine = factory.getEngineByName("JavaScript");
//  try {
//  // String script = "function load(url){var dom=null;if(document.implementation && document.implementation.createDocument){dom=new window.XMLHttpRequest();}else{dom=new ActiveXObject(\"Microsoft.XMLHttp\");} dom.open(\"GET\",url,false); dom.send(null); return dom;}";
//   
//  // se.eval(script);
//   Invocable inv2 = (Invocable) se;
//   String res=(String)inv.invokeFunction("load",url);
//   
//   System.out.println(res);
//   }catch(Exception e){e.printStackTrace();}  
 }
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值