Link Webkit to your native environment

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

For example, is it possible to pull out an html view from the Internet and fill out a form in that view with data stored on my device?

+2
source share
2 answers

Yes on Android using addJavaScriptInterface () .

class MyInterface { private String someData; public String getData() { return someData; } } webview.addJavaScriptInterface(new MyInterface(), "myInterface"); 

And in html in your webview.

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

By the way, if the webpage you are using does not belong to you (so you cannot change it), you can insert javascript inline. For instance:

 webview.loadUrl("javascript:document.getElementById('someTextField').value = myInterface.getData();"); 
+8
source

For iPhone, you can call the JavaScript function from Objective-C using stringByEvaluatingJavaScriptFromString .

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

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

All Articles