开发者

How can I open a webpage within a Java app and run my own javascript code

I would like to open a webpage and run a javascript code from within a java app. For example I would like to open the page www.mytestpage.com and run the following javascript code:

document.getElementById("txtEmail").value="test@hotmail.com";
submit();
void(0);
开发者_JAVA技巧

This works in a browser...how can I do it programatically within a java app?

Thanks!


You can use Rhino to execute JavaScript but you won't have a DOM available - i.e. document.getElementById() would work.

You can use HTML Unit (headless) or WebDriver/Selenium (Driving a browser) to execute JavaScript in an environment that has a DOM available.


I'm not sure what you are looking for but I assume that you want to write automated POST request. This can be done in with Http Client library. Only you have to set appropriate request (POST or GET) parameters.

Look at examples - with this library you can do basic authentication or post files too.


Your question is a bit ambiguous, as we don't know the position of the Java program.
If that's a Java applet inside your page, you should look at Java<->JavaScript interaction, it works well.
If you need a separate Java program to control a browser, like sending a bookmarklet in the address bar (as one of your tags suggests), it is a bit harder (depends on target browser), perhaps look at the Robot class.


There's Rhino JS engine written in Java that you can run on app server such as Tomcat and feed JS to, however - it's not clear what are you trying to do with this?

There's also Envjs simulated browser environment which is based on Rhino but complete enough to run jQuery and/or Prototype


DWR (and other frameworks) now support "reverse ajax." The general idea is that you use one of three methods to communicate back to the client:

  1. Comet (long-lived https session)
  2. Polling
  3. opportunistic / piggy-back (i.e. next time a request comes from the client, append your js call)

Regardless of method (which is typically a configuration-time decision and not a coding issue), you will have full access to any/all js calls you want to make.

Check out the reference page from DWR to get a pretty good explanation.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜