This post answers the following questions:
- How can I send a message from a UIWebView to my class?
- How can I take an action based on an event in a UIWebView?
In the last post, we discussed creating navigation for a UIWebView, and used the stringByEvaluatingJavaScriptFromString: function as well as the shouldStartLoadWithRequest: delegate method. In this post, we’re going to use both of those functions to get messages from the UIWebView to your Objective-C code.
The first way to get a message from your UIWebView is asynchronous. All one must do is query the DOM using JavaScript. Let’s say you had the following in your HTML:
<input id="fourten" />
…and you wanted to find out what a user had typed in this text box. All one would need to return the contents of the text box is:
[wWw stringByEvaluatingJavaScriptFromString:@"document.getElementById('fourten').value;"];
This is great if you just need to check the present value of something. If you want to know when a user takes an action within the UIWebView, you’ll need a little bit more than this; otherwise, you’d be polling the UIWebView constantly. We can accomplish this using the other function we talked about last week.
Set up your UIWebView, and load in the following HTML:
<form action="http://message/">Tell me something: <input id="fourten" /><br /><input type="submit" value="Go!" /></form>
This naturally presents a text box and a submit button, and when the submit button is pressed, the data is sent to http://message/, a fictitious address. But, before the data can be sent, the iPhone platform will consult shouldStartLoadWithRequest: to find out if we should proceed with that page load. Instead, we’ll hijack that form submission and run our own code:
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request {
if([[request.URL absoluteString] isEqualToString:@"http://message/"]) {
// do stuff
return NO;
}}
return YES;
The code above detects when the user is attempting to hit our fictitious address. We can perform an action and then return NO to let the UIWebView know that it need not actually load our fictitious address. All other attempts to load a page are met with a YES return.
You may also (and frequently will want to!) combine these two methods: use the later to know when to read the data, and the former to read the data. That is, in place of // do stuff you can use the stringByEvaluatingJavaScriptFromString: function to get data out of as many form fields (including hidden form fields) as you’d like.
This is a four-part series on the UIWebView — please check back for more if you’re looking to go deeper.
FourTen Technologies, Inc., is a leading US iPhone app development firm. For information on having FourTen build a custom mobile application for your company, visit www.fourtentech.com. Article written by Jonathan Corbett (President & CEO, FourTen). Contact: jcorbett@fourtentech.com.