Android, Webview, get submitted form data - android

I want my Android application to use Webview to display an html form. When the user presses the Submit button, it want the name/value pairs sent back to my program. How do I do this?
I have looked at other similar questions but not of the responses tell how, specifically, to do this.

Look into the use of Javascript interfaces within WebView. Please see this area of the Android Developers Guide. Basically, you should be able to communicate from the page to the device with the Javascript interface and let your WebView Activity know when the submit button is pressed and send its values over.

I have found what I needed. If I set action='FORM" in the form html, then I can intercept the action with:
public void onLoadResource (WebView view, String url){
int index = url.indexOf("FORM?");
if (index != -1){
String d = URLDecoder.decode(url.substring(index+5));
}
}
The name/value pairs are in String d.

If you want to save Name/Value pairs and are willing to use jQuery then it's quite simple.
Assuming you put jQuery in your assets folder you can read it into a file from:
getResources().getAssets()
In the WebViewClient that you set (assuming you overrode the client) you can do:
view.loadUrl("javascript:" + escapedJqueryStringHere);
Then, make sure you have a JavascriptInterface configured for your webview with a method, for example, called 'ReturnJSONFromForm(String json)' configured for "MyJInterface" then load the form into the page and then try this:
webview.loadUrl("javascript:MyJInterface.ReturnJSONFromForm($(\"form\").serialize());");
Now in your interface, just create a JSONObject from the resultant string and there you go! Name/Value pairs from your form.
Serialize won't capture disabled fields or submit buttons.. if you need that, then a more complex javascript solution exists but it's far more difficult.

Related

Find language of a site loaded in my webview

I have a webview where external url will be launched and loaded in the webview.
So, I want to find what language the webpage is? is it possible in android webview?
After scanning the documentation it doesn't look like there's an explicit method in the WebView class that allows you to retrieve the language used by the web page.
An alternative way of finding out the language of a web page would be to download the raw HTML content of the page using the JSoup library and parsing it for the lang attribute. However, this would obviously require that the owner of the page specified that attribute when creating the page.
Here's a snippet of how you can use JSoup to get the raw HTML content of the page you're trying to load:
Document htmlDoc = Jsoup.connect("http://en.wikipedia.org/").get();
Then, to parse for the lang attribute (which is used to specify the natural language of the content found on the web page), you would do this (credit to this OP):
Element html = htmlDoc.select("html").first();
String langAttr = htmlDoc.attr("lang"); //check that this isn't null before using it
Hope this helps. But to answer your original question - no, the WebView class doesn't have an explicit method to obtain the language of a web page included out of the box.

android: Put Text into a TextBox in Webview

I write an app for android. There is a Webview and I want to put Text into the focussed TextArea on the website after clicking a button at my app. I haven't found any solution at google.
It is important to put in the text, it is no login view, where data can be transmitted by the POST methode, the user should be able to see the input.
I hope you can help me.
Thanks!
public void addJavascriptInterface (Object object, String name)
Added in API level 1
Injects the supplied Java object into this WebView. The object is injected into the JavaScript context of the main frame, using the supplied name. This allows the Java object's methods to be accessed from JavaScript. For applications targeted to API level JELLY_BEAN_MR1 and above, only public methods that are annotated with JavascriptInterface can be accessed from JavaScript. For applications targeted to API level JELLY_BEAN or below, all public methods (including the inherited ones) can be accessed, see the important security note below for implications.
Note that injected objects will not appear in JavaScript until the page is next (re)loaded. For example:
class JsObject {
#JavascriptInterface
public String toString() { return "injectedObject"; }
}
webView.addJavascriptInterface(new JsObject(), "injectedObject");
webView.loadData("", "text/html", null);
webView.loadUrl("javascript:alert(injectedObject.toString())");
IMPORTANT:
This method can be used to allow JavaScript to control the host application. This is a powerful feature, but also presents a security risk for applications targeted to API level JELLY_BEAN or below, because JavaScript could use reflection to access an injected object's public fields. Use of this method in a WebView containing untrusted content could allow an attacker to manipulate the host application in unintended ways, executing Java code with the permissions of the host application. Use extreme care when using this method in a WebView which could contain untrusted content.
JavaScript interacts with Java object on a private, background thread of this WebView. Care is therefore required to maintain thread safety.
The Java object's fields are not accessible.
Parameters
object the Java object to inject into this WebView's JavaScript context. Null values are ignored.
name the name used to expose the object in JavaScript
I am using phone, sorry for formating. This is quote from offical page android.
So:
If is your page:
Set ID of Input, for example text (for example: <input id="text" ...)
Add this code of end of document:
<script>function a(b){document.getElementById("text (here is yur ID)").value=b;};function b(a){document.getElementById("text (here is your ID)").value+=a;}</script>
To change text, use this code:
String str="any string";
webview.loadUrl("javascript:a(\""+str+"\")");
To add text at the end:
String str="any string";
webview.loadUrl("javascript:b(\""+str+"\")");

Fill a HTML5 List with data from Android/Java Code

i want to populate a List in an HTML5 File (displayed within a WebView) with data from Android Code (for exmaple from an ArrayList). Can anyone please tell me how or if this is possible.
Thanks in advance
Thommy
With a WebView you can simply:
webview.loadUrl("javascript:YOURJAVASCRIPTCODE");
Your javascript code could be something like:
document.getElementById('txtField1').value = "test";
Read this:
http://developer.android.com/guide/webapps/webview.html#BindingJavaScript
You can expose anything from your Android code. If you return some JSON (array or object), you can build your list (or anything else) using some javascript.

Save images inside webview Android SDK

Im making a simple app for some friends to use on there android phone that shows my website with images. Im using a webview to show the website inside the app. I want the users, to be able to save the actual image. Either by Hold down on the image or actually clicking a button. Been looking around on googles docs ands cant seem to find anything for this.
I haven't actually played around with this yet, but from the docs it appears you have at least two (non-deprecated) options:
getHitTestResult()
requestImageRef(Message msg)
According to the documentation you can use the first option to test for IMAGE_TYPE as result, and a url to the image is provided as well:
If a HTML::img tag is found, the HitTestResult type is set to
IMAGE_TYPE and the url is set in the "extra" field.
The second option will give you a similar result:
Request the url of the image last touched by the user. msg will be
sent to its target with a String representing the url as its object.
Not sure if these options are compatible with a 'long click' too though.
Alternatively, how did you have in mind to link clicking a button to a specific image? Depending on your solution for this, you may also be able to simply capture all loaded image resources using onLoadResource(WebView view, String url), build a list of image references and download the one that button click refers too.

Determine element of url from webview shouldOverRideUrlLoading

I am displaying a html in a custom activity with a webview. I am overriding
public boolean shouldOverrideUrlLoading(WebView view, String url) {
to intercept certain urls. Now I would like to be able to figure out some more details about the html around that url.
In my case I would like to get the html element that contains the url. E.g. if the url comes from
Manfred Moser
I would like to be able to somehow retrieve the value "Manfred Moser" from within the anchor tag. Is there a way to do that. I found that you do not have access to the DOM from Java.
One way I can think of would be to download the page separately and parse it all before even loading it in webview. However that is an ugly hack at best. Is there a better way?
There is a dirty hack:
Bind some Java object so that it can be called from Javascript with WebView:
addJavascriptInterface(javaObjectExposed, "JSname")
Force execute javascript within an existing page by
WebView.loadUrl("javascript:window.JSname.passData("some data");");
Described here: http://lexandera.com/2009/01/extracting-html-from-a-webview/
Note: this is a security risk - any JS code in this web page could access/call your binded Java object. Best to pass some one-time cookies to loadUrl() and pass them back your Java object to check that it's your code making the call.
In addition to #Peter Knego's approach, there is the inverse:
Use addJavascriptInterface(), per his step #1
For your link, use an onClick attribute on your <a> tag to call out some method on the Java object from step #1, where the Java object turns around and loads the URL into the WebView, and supplies whatever sort of identifying information you want.
Suffice it to say, there's no way to get the information you want from shouldOverrideUrlLoading().

Categories

Resources