Communicating with a Web View

Having loaded a web view with content, you don’t so much configure or command the web view as communicate with it. There are two modes of communication with a web view and its content:

Load requests

When a web view is asked to load content, possibly because the user has tapped a link within it, its delegate is sent the message webView:shouldStartLoadWithRequest:navigationType:. This is your opportunity to interfere with the web view’s loading behavior; if you return NO, the content won’t load.

The second argument is an NSURLRequest, whose URL property you can analyze (very easily, because it’s an NSURL). The third argument is a constant describing the type of navigation involved, whose value will be one of the following:

  • UIWebViewNavigationTypeLinkClicked
  • UIWebViewNavigationTypeFormSubmitted
  • UIWebViewNavigationTypeBackForward
  • UIWebViewNavigationTypeReload
  • UIWebViewNavigationTypeFormResubmitted
  • UIWebViewNavigationTypeOther (includes loading the web view with content initially)
JavaScript execution
You can speak JavaScript to a web view’s content by sending it the stringByEvaluatingJavaScriptFromString: message. Thus you can enquire as to the nature and details of that content, and you can alter the content dynamically.

The TidBITS News app uses webView:shouldStartLoadWithRequest:navigationType: to distinguish between the user tapping an ordinary link and tapping the Listen button (shown in Figure 24-2). The onclick script for the <a> tag surrounding ...

Get Programming iOS 6, 3rd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.