我能够从Webview中的javascript / local html向Java发送一个简单的字符串 如何将整个表单对象发送到Java?
public class JFXTest1 extends Application {
WebView webview = new WebView();
webview.getEngine().load(JFXTest1.class.getResource("local1.html").toExternalForm());
JSObject jsobj = (JSObject) webview.getEngine().executeScript("window");
Local1JSBridge bridge = new Local1JSBridge();
bridge.setWindow(jsobj);
jsobj.setMember("java", bridge);
我的桥梁。
public class Local1JSBridge {
public void printFormData(String data1){
System.out.println( data1);
}
}
调用Java类中方法的javascript部分。
<html>
<head></head>
<body>
hi :)
<form id="form1" name="form1">
<input type="text" id="text1">text value</input>
</form>
<button onclick="java.printFormData(document.getElementById('text1').value);">Submit</button>
<br/>
<button onclick="java.exit()">Exit</button>
</body>
答案 0 :(得分:1)
我无法找到一种方法来实际获取表单数据而不在HTML文档中执行Javascript,但以下似乎基本上可以工作:
public void printFormData(Object form) {
System.out.println(form.getClass() + " " + form);
if (form instanceof Element) {
NodeList inputs = ((Element)form).getElementsByTagName("input");
for (int i = 0 ; i < inputs.getLength(); i++) {
Node input = inputs.item(i);
Element inputEl = (Element)input ;
String id = inputEl.getAttribute("id");
String value = (String) engine.executeScript(id+".value");
System.out.printf("%s : %s %n", id, value);
}
}
}
然后在HTML中:
<html>
<head></head>
<body>
hi :)
<form id="form1" name="form1">
<input type="text" id="text1">text value</input>
</form>
<button onclick="java.printFormData(document.getElementById('form1'));">Submit</button>
<br/>
<button onclick="java.exit()">Exit</button>
</body>
</html>