2012-04-05 32 views
0

我使用特定的JavaScript连接到网络服务器。 (使用HttpURLConnection atm) 我需要的是一个可以操纵JavaScript函数的连接。 然后我想再次运行整个JavaScript。使用Java操作JavaScript

我想总是下面的函数返回“新FlashSocketBackend()”

function createBackend() { 
    if (flashSocketsWork) { 
     return new FlashSocketBackend() 
    } else { 
     return new COMETBackend() 
    } 
} 

我是不是要可以使用HtmlUnit这个? 连接,操作和重新运行脚本的最简单方法是什么?

谢谢。

+0

你的意思为 “操纵的JavaScript函数” 是什么?您希望浏览器向服务器发送JavaScript代码,或者在连接后,服务器能够在客户端上调用JavaScript函数? – dash1e 2012-04-05 10:39:45

+0

我不确定这是否合理。 HttpURLConnection是一个Java类。 Java和JavaScript之间基本上没有关系。也许试着重述一下你的问题。 – 2012-04-05 10:41:01

+0

是的,我想改变一个函数,之后服务器会调用它。 – Tom 2012-04-05 10:42:11

回答

0

有了HtmlUnit,你确实可以做到。

尽管您无法操作现有的JS函数,但是您仍然可以在现有页面上执行您希望的JavaScript代码。

例子:

WebClient htmlunit = new WebClient(); 
HtmlPage page = htmlunit.getPage("http://www.google.com"); 
page = page.executeJavaScript("<JS code here>").getNewPage(); 

//manipulate the JS code and re-excute 
page = page.executeJavaScript("<manipulated JS code here>").getNewPage(); 

//manipulate the JS code and re-excute 
page = page.executeJavaScript("<manipulated JS code here>").getNewPage(); 

更多: http://www.aviyehuda.com/2011/05/htmlunit-a-quick-introduction/

0

最好的办法可能是使用Rhino--一个完全用Java编写的JavaScript的开源实现。使用window.location载入您的页面,并希望运行您的JavaScript函数。我在Bringing the Browser to the Server之前有一段时间阅读,似乎是可能的。