3

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?

JLeonard
  • 8,520
  • 7
  • 36
  • 36

2 Answers2

9

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 = myInterface.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 = myInterface.getData();");
Barney
  • 16,181
  • 5
  • 62
  • 76
Robby Pond
  • 73,164
  • 16
  • 126
  • 119
  • 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 Jul 15 '10 at 15:40
  • 1
    @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 Jul 15 '10 at 15:44
0

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);
Sharjeel Aziz
  • 8,495
  • 5
  • 38
  • 37