views:

123

answers:

5

Hi, I would like to open a webpage and run a javascript function 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="[email protected]";submit();void(0);

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

Thanks!

A: 

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

DroidIn.net
A: 

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.

leonm
A: 

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.

cetnar
A: 

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.

PhiLho
A: 

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.

ikelly