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
URLproperty 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 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access