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.
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();
}
Java Scripting Programmer's Guide
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.
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.
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 ?
精彩评论