If you need to make AJAX calls for cross-site services in WebView, you can circumvent security restrictions by making your AJAX calls redirected to Java. For example, you could write or find a class with the ".request ()" method that takes JSObject as a parameter (the same JSObject format, which preferably uses the jQuery $ .ajax () method) and inserts a Java object that will expose this method:
WebView myWebView; //assuming it initialized and points to an actual WebView WebEngine engine = myWebView.getEngine(); JSObject window = null; try{ window = (JSObject) engine.executeScript("window"); }catch (JSException e){ e.printStackTrace(); } if (window != null){ window.setMember("myAjax", new AJAXProxyClass()); }
You can also directly override the jQuery ajax method with your own upcalling method, so the difference is completely transparent to javascript code, i.e.:
engine.executeScript("$.ajax = new function (o) { myAjax.request(o); };"); engine.executeScript("_$ = window.$");
This will replace the jQuery "$ .ajax" call using one of your Java object without any problems. (I set the variable "_ $" because jQuery will overwrite $ with it sometimes if it detects conflicts, returning jQuery to its original version.) This means that in most cases, any javascript code does not have to worry about working whether it is in your webview or not.
A warning, however, is that the jQuery ajax call is quite complicated, and this may break some jQuery ajax extensions if you are not careful about how you handle it. It should work fine for the most common types of GET and POST calls.
source share