Pulling a single variable off a webview in iPhone?
I am 1 week into "brand new" to iOS. I am using x-code to create a view based app. Now using a web view I need to pull a variable from a hidden tag on the webpage and send it to native code. So how do I do this:
xmlhttp=new XMLHttpRequest();
开发者_运维技巧
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
**this varSendText**
varSendText = document.getElementById("sendtextcoupon").value;
if (varSendText == "1")..........
That is the goal but obviously not the way.
Use the stringByEvaluatingJavaScriptFromString:
method of the UIWebView
.
NSString *varSendText = [webView stringByEvaluatingJavaScriptFromString:@"return varSendText;"];
Just make sure the variable is global and the AJAX response has been received. You can also check this by using the above method and simple Javascript.
Class Reference: http://developer.apple.com/library/ios/#documentation/uikit/reference/UIWebView_Class/Reference/Reference.html
Not sure if it's what you need, but you can execute arbitrary javascript on a web view using
[webView stringByEvaluatingJavaScriptFromString:script]
If script
were something along the lines of:
@"return varSendData;"
That would do it in a normal case. I'm not sure how the xmlhttprequest callback makes it different. I'm not up on my ajax. I assume you'll have to find some way to wait until the call succeeds.
Edit: Somebody beat me to the punch apparently. So there you go. We've all suggested the same thing!
If you want to call OUT of your UIWebView into the app (which is what I think you're asing, vs INTO your UIWebView which is what the other current answers are addressing), you have to kick off a page-load from your content, either using javascript, or some user interaction like a hyperlink being followed. Your app can cancel the page load so that the page doesn't actually navigate away. You can pass data out as parameters on the page load request url. You cant get any 'return value', but you can use what others have suggested (calling stringByEvaluatingJavaScriptFromString:
) to pass data back in based on the result of whatever action you took for the pageLoad request.
The page load request is intercepted by your UIWebViewDelegate method:
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
javascript to kick off the page load request can be something like this:
document.location = 'command://dosomething?param1=something¶m2=more'
Here's a a page that has a more complete sample, in the section titled 'Javascript communicating back with Objective-C code':
http://www.codingventures.com/2008/12/using-uiwebview-to-render-svg-files/
精彩评论