简体   繁体   English

从 Java 运行 Javascript(但需要 jQuery、DOM 和 ajax)

[英]Running Javascript from Java (but need jQuery, DOM and ajax)

I'm building a web app with Diagram in it.我正在构建一个带有图表的网络应用程序。

For the diagram I used jsPlumb library Link: https://jsplumbtoolkit.com/对于图表,我使用了 jsPlumb 库链接: https ://jsplumbtoolkit.com/

One of my requirement is to make Blocks inside the Diagram like flowchart.我的要求之一是像流程图一样在图表中制作块。 And one type of the blocks is a able to be inserted by customizable script.一种类型的块可以通过可定制的脚本插入。 So, when user double-clicked that block, they can input Javascript code in the textarea and will be executed later.因此,当用户双击该块时,他们可以在 textarea 中输入 Javascript 代码并稍后执行。

Here lies my problem : I able to run the script code very well, when it is still on the front-end side (jsp) using browser using "new Function" from Javascript.这就是我的问题:我能够很好地运行脚本代码,当它仍然在前端(jsp)使用浏览器使用来自 Javascript 的“新函数”时。 But after the block is saved, the script saved to DB.但是块保存后,脚本保存到DB。 And if I need to run it again, then it will be executed from back-end (Java).如果我需要再次运行它,那么它将从后端(Java)执行。

Therefore, I used ScriptEngine to run the Javascript.因此,我使用 ScriptEngine 来运行 Javascript。 The problem is ajax, $-sign, console, etc are not recognized from Java.问题是 Java 无法识别 ajax、$-sign、控制台等。 And I found out later, that ScriptEngine did not support for those kind of things.后来我发现,ScriptEngine 不支持那些东西。

So, I wonder is there is any possible way to make these possible ?所以,我想知道是否有任何可能的方法使这些成为可能? I'm open to other alternative idea.我对其他替代想法持开放态度。

Thank you谢谢

Use HtmlUnit Java Library使用HtmlUnit Java 库

Sample code示例代码

final WebClient webClient = new WebClient(BrowserVersion.CHROME);
final HtmlPage page = webClient.getPage("http://127.0.0.1:9090/mysite");
page.executeJavaScript("$");
webClient.close();

This http://127.0.0.1:9090/mysite can be your local website which already has jquery这个http://127.0.0.1:9090/mysite可以是你本地已经有 jquery 的网站

You can also inject a script tag on the fly in a blank html page您还可以在空白 html 页面中动态注入脚本标记

If your are behind a proxy then如果您在代理后面,那么

final WebClient webClient = new WebClient(BrowserVersion.CHROME, "proxyhost", 8080);

Alternate Idea替代想法

Use Jaunt - Java Web Scraping & JSON Querying Java Library使用Jaunt - Java Web Scraping & JSON Querying Java Library

Sample code and full documentation available in the site站点中提供的示例代码和完整文档

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM