Give the HTML of a webpage in a String variable, how can I execute JavaScript in it by using Rhino?
I've read the tutorial on Rhinos homepage without any luck.
-
5Rhino is just a javascript interpreter, it's not tied to the DOM and it doesn't interpret HTML. Are you sure that you're not looking for a web browser container in java ?HoLyVieR– HoLyVieR2011年08月27日 16:51:59 +00:00Commented Aug 27, 2011 at 16:51
4 Answers 4
You can use the Java Scripting Engine JSR-223.
ScriptEngineManager mgr = new ScriptEngineManager();
ScriptEngine jsEngine = mgr.getEngineByName("JavaScript");
try {
jsEngine.eval("print('Hello, world!')");
} catch (ScriptException ex) {
ex.printStackTrace();
}
Comments
HtmlUnit is a product built on top of Rhino which allows the testing of web applications that contain client-side JavaScript. I have not used it myself but recommended it to one developer who did and was very pleased by it.
It's hard to know whether this is what you want, as your original question doesn't say much about why you want to execute the JavaScript in the first place.
Comments
You can't do that in any direct way. Rhino is a JavaScript interpreter, but that certainly does not mean it can do what a web browser does.
Your HTML source may have <script> blocks in it and it may reference external scripts. Even if you were able to extract the script sources from the HTML — which you'd have to do, as Rhino doesn't know anything at all about HTML — you'd be faced with a bigger problem: the DOM.
What you probably should be working with is some sort of embedded (or slave) browser solution.
Comments
Rhino will only allow you to execute standalone JavaScript.
If you want to run JavaScript in HTML, you need a browser to provide runtime - you can use WebDriver for that.
What are you trying to do ?