使用Java操作JavaScript

Manipulate JavaScript using Java

本文关键字:JavaScript 操作 Java 使用      更新时间:2023-09-26

我正在连接到一个具有特定JavaScript的Web服务器。(使用HttpURLConnection atm)我需要的是一个可以操作JavaScript函数的连接。之后我想再次运行整个JavaScript。

我希望以下函数始终返回"new FlashSocketBack()"

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

我必须使用HtmlUnit吗?连接、操作和重新运行脚本的最简单方法是什么?

谢谢。

使用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/

你最好的办法可能是使用Rhino——一种完全用Java编写的JavaScript的开源实现。用window.location加载您的页面,并希望运行您的JavaScript函数。在将浏览器带到服务器之前,我读过一些书,这似乎是可能的。