views:

64

answers:

2

If I have a webkit view loaded in my Android or iPhone app, can I pass data back and forth from the page in webkit?

For example, can I pull an html view down from the web and populate a form in that view with data stored on my device?

+2  A: 

Yes in Android using addJavaScriptInterface().

class MyInterface {
    private String someData;
    public String getData() { return someData; }
}

webview.addJavaScriptInterface(new MyInterface(), "myInterface");

And in the html in your webview.

<script type="text/javascript">
     var someData = myIterface.getData();
</script>

By the way, if the webpage you are using is not yours (so that you can't modify it), you can insert javascript inline. For instance:

webview.loadUrl("javascript:document.getElementById('someTextField').value = myIterface.getData();");
BrennaSoft
If I understand correctly, this requires you to modify the html to insert the javascript block... could get hairy. Also, take careful note of the security considerations on the Android Developer site.
Pontus Gagge
@Pontus it would only require you to modify the HTML of the page at runtime if the page isn't owned/designed by you. If you are loading from a local resource or from a site you control then you don't need any crazy injection techniques. It's extremely beneficial under some circumstances to know what capabilities are available and how to use it though.
Quintin Robinson
A: 

For iPhone you can call a JavaScript function from Objective-C by using stringByEvaluatingJavaScriptFromString.

For instance, to get the value of an input field named "fname":

NSString * fString =[webView stringByEvaluatingJavaScriptFromString:@"document.getElementByName(\"fname\").value"]; 
NSLog(@"fString: %@",fString);
Shaji