问题描述
如果我在Android或iPhone应用中加载了WebKit视图,我可以从WebKit的页面来回传递数据吗?
例如,我可以从网络上拉下HTML视图并在该视图中使用存储在设备上的数据填充表单?
推荐答案
是在Android中使用 addjavascriptInterface().
class MyInterface { private String someData; public String getData() { return someData; } } webview.addJavaScriptInterface(new MyInterface(), "myInterface");
以及您的WebView中的HTML.
<script type="text/javascript"> var someData = myInterface.getData(); </script>
顺便说一句,如果您使用的网页不是您的(因此您不能修改它),则可以 insert javascript内联.例如:
webview.loadUrl("javascript:document.getElementById('someTextField').value = myInterface.getData();");
其他推荐答案
对于iPhone,您可以使用iphone/library/documentation/uikit/uiikit/reiwebview_class/reference/reference/reference/reference/reference/reference/reference/reference/reference/reference/reperfience
其他推荐答案
您可以从Objective-C调用JavaScript函数.
例如,获取名为" fname"的输入字段的值:
NSString * fString =[webView stringByEvaluatingJavaScriptFromString:@"document.getElementByName(\"fname\").value"]; NSLog(@"fString: %@",fString);
问题描述
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?
推荐答案
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();");
其他推荐答案
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);